gojira
gojira

Reputation: 33

Regex Gets Match Wrong

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?

Upvotes: 2

Views: 84

Answers (2)

Anirudha
Anirudha

Reputation: 32797

- 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]+$   
             ^

Upvotes: 10

anubhava
anubhava

Reputation: 785176

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]+$ 

Upvotes: 2

Related Questions