Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Gets Match Wrong

Tags:

.net

regex

This Regex:

^[a-zA-Z0-9 -.,()/\n/\r]+$  

in .NET always matches

"#" or "$" or "!" or "%" or "&" or "*" or "+"

So to be clear, this line:

Regex.IsMatch("!", @"^[a-zA-Z0-9 -.,()/\n/\r]+$");

returns true. Why does that happen?

like image 726
gojira Avatar asked Feb 06 '26 02:02

gojira


2 Answers

- when used within character class depicts a range

So you are trying to match characters from space till .

Move - to end or the beginning of character class or escape it \-

Now referring to ascii table you are specifying a range from ascii decimal value 32 till 46 which includes !,",#,$,%........


So,it should be

^[-a-zA-Z0-9 .,()/\n/\r]+$ 
  ^

or

^[a-zA-Z0-9 .,()/\n/\r-]+$   
                      ^

or escape it

^[a-zA-Z0-9 \-.,()/\n/\r]+$   
             ^
like image 89
Anirudha Avatar answered Feb 08 '26 04:02

Anirudha


Hyphen in a character class needs to be either at first or at last position otherwise it needs to be escaped. It should work:

^[a-zA-Z0-9 .,()/\n/\r-]+$ 

Or:

^[-a-zA-Z0-9 .,()/\n/\r]+$ 

Or:

^[a-zA-Z0-9 \-.,()/\n/\r]+$ 
like image 45
anubhava Avatar answered Feb 08 '26 04:02

anubhava



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!