Reputation: 13742
I am trying to validate a string based on the inputed characters. I want to be able to set which characters are allowed besides characters and numbers. Below is my extension method:
public static bool isAlphaNumeric(this string inputString, string allowedChars)
{
StringBuilder str = new StringBuilder(allowedChars);
str.Replace(" ", "\\s");
str.Replace("\n","\\\\");
str.Replace("/n", "////");
allowedChars = str.ToString();
Regex rg = new Regex(@"^[a-zA-Z0-9" + allowedChars + "]*$");
return rg.IsMatch(inputString);
}
The way I use this is:
s string = " te\m@as 1963' yili.ışçöÖÇÜ/nda olbnrdu" // just a test string with no meaning
if (s.isAlphaNumeric("ışŞö\Ö@üÜçÇ ğ'Ğ/.")) {...}
Of course it gives an error:
parsing "^[a-zA-Z0-9ışŞö\Ö@üÜçÇ\sğ'Ğ/.]*$" - Unrecognized escape sequence
the stringbuilder replace function is wrong which I am aware of. I want to be able to accept all characters given in the allowedChars parameter. This can also include slashes (any other characters similar to slashes I am not aware of?) Given this, how can I get my replace function work? and also is the way I am doing is correct? I am very very new to regular expressions and have no clue on how to work with them...
Upvotes: 1
Views: 468
Reputation: 21568
You need to use Regex.Escape
on your string.
allowedChars = Regex.Escape(str.ToString());
ought to do it.
Upvotes: 7