Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression C# IsMatch()

Tags:

c#

regex

I try to use regular expression to check if a string contains only: 0-9, A-Z, a-z, \, / or -. I used Regex validator = new Regex(@"[0-9a-zA-Z\-/]*"); and no matter what string I introduce is valid.

The check look like this: if(!validator.IsMatch(myString))

What's wrong?

like image 313
Ale Avatar asked Aug 25 '26 18:08

Ale


1 Answers

If I understand what you want. I believe your pattern should be

new Regex(@"^[0-9a-zA-Z\\\-/]*$");

The ^ and $ symbols are anchors that match the beginning and end of the string, respectively. Without those, the pattern would match any strings that contain any character in that class. With them, it matches strings that only contain characters in that class.

You also specified you wanted to include backslash characters, but the original pattern had \- in the character class. This is simply an escape sequence for the hyphen within the character class. To also include backslash in the character class you need to specify that separately (escaped as well). So the resulting character class has \\ (backslash) followed by \- (hyphen).

Now, this will still match empty strings because * means "zero-or-more". if you want to only match non-empty strings use:

new Regex(@"^[0-9a-zA-Z\\\-/]+$");

The + means "one-or-more".

like image 100
p.s.w.g Avatar answered Aug 28 '26 08:08

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!