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?
- 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]+$
^
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]+$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With