Skip to content

Instantly share code, notes, and snippets.

@lsancho
Created April 19, 2018 14:42
Show Gist options
  • Save lsancho/462d3f338d5037b6cbbf3adc78584bb2 to your computer and use it in GitHub Desktop.
Save lsancho/462d3f338d5037b6cbbf3adc78584bb2 to your computer and use it in GitHub Desktop.
used to remove characters not allowed in product names
using System.Text.RegularExpressions;
namespace Utils.Text
{
public static class NotAllowedCharacters
{
private const string AccentsCharactersAllowed = "áéíóúâêîôûãõàèìòùäëïöüçñÁÉÍÓÚÂÊÎÔÛÃÕÀÈÌÒÙÄËÏÖÜÇÑ`´";
private const string SpecialCharactersAllowed = "-+÷\\/><=≠.,:;\'\"!¡?¿{}[]()@#*&€$%*°ºª²³⅓⅔⅛⅜⅝⅞_";
public static bool Contains(string text)
{
return !string.IsNullOrWhiteSpace(text) && (!Regex.IsMatch(text, PatternAllowedCharacters) || Regex.IsMatch(text, PatternDoubleSpaces));
}
public static string Replace(string text, char? replacement = null)
{
return string.IsNullOrWhiteSpace(text) ? text : Regex.Replace(Regex.Replace(text, PatternNotAllowedCharacters, ""), PatternDoubleSpaces, " ");
}
private static string PatternAllowedCharacters => $"^[{ToRegexString(SpecialCharactersAllowed)}{ToRegexString(AccentsCharactersAllowed)} a-zA-Z0-9]+$";
private static string PatternNotAllowedCharacters => $"[^{ToRegexString(SpecialCharactersAllowed)}{ToRegexString(AccentsCharactersAllowed)} a-zA-Z0-9]";
private static string PatternDoubleSpaces => $"\\s\\s+";
private static string ToRegexString(string text)
{
return text
.Replace("(", "\\(")
.Replace(")", "\\)")
.Replace("[", "\\[")
.Replace("]", "\\]");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment