Reputation: 1511
Im checking some strings with my regex and somehow its not perfect. Im not sure why. I would like to allow string with only these characters:
So I thought this regex should be enough:
Regex("[^A-Z0-9.$/+%\\- ]$")
But with some string its not really working. I made a small example:
static Regex regex = new Regex("[^A-Z0-9.$/+%\\- ]$");
static void Main()
{
string s;
Console.WriteLine("check: \n");
s = "?~=) 2313";
Console.WriteLine(s + ": " +IsValid(s));
s = "ÄÜÖ";
Console.WriteLine(s + ": " + IsValid(s));
s = "Ü~=) 2313";
Console.WriteLine(s + ": " + IsValid(s));
s = "Ü 2313";
Console.WriteLine(s + ": " + IsValid(s));
s = "~=) 2313 Ü";
Console.WriteLine(s + ": " + IsValid(s));
s = "ÜÜÜ";
Console.WriteLine(s + ": " + IsValid(s));
s = "~=)";
Console.WriteLine(s + ": " + IsValid(s));
s = "THIS--STRING $1234567890$ SHOULD BE VALID.%/ +";
Console.WriteLine(s + ": " + IsValid(s));
Console.ReadKey();
}
public static bool IsValid(string input)
{
if (regex.IsMatch(input)) return false;
return true;
}
As output I get:
The 1.,3. and 4. are True, but this is wrong. What is wrong with my regex? Any ideas? Thank you
Upvotes: 1
Views: 82
Reputation: 32797
It should be
^[A-Z0-9.$/+%\\- ]+$
| ||match end of the string
| |
| |match one or more characters of [A-Z0-9.$/+%\\- ]
|start of the string
You need to use quantifiers like +
,*
to match multiple characters
Your IsValid Class should be
public static bool IsValid(string input)
{
if (regex.IsMatch(input)) return true;
return false;
}
Upvotes: 1
Reputation:
Your regex is matching only one character that is not any of those characters. Your regex should be:
^[A-Z0-9\.$/+% ]+$
Also, use a non-inverted function for your check:
public static bool IsValid(string input)
{
if (regex.IsMatch(input)) return true;
return false;
}
Upvotes: 0
Reputation: 5930
Try this regex (Did you mean to include -
in your description of allowed characters?):
Regex("^[A-Z0-9.$/+% -]*$")
Upvotes: 1