How to match hyphens with Regular Expression?
How to rewrite the [a-zA-Z0-9!$* \t\r\n]
pattern to match hyphen along with the existing characters ?
Solution 1:
The hyphen is usually a normal character in regular expressions. Only if it’s in a character class and between two other characters does it take a special meaning.
Thus:
-
[-]
matches a hyphen. -
[abc-]
matchesa
,b
,c
or a hyphen. -
[-abc]
matchesa
,b
,c
or a hyphen. -
[ab-d]
matchesa
,b
,c
ord
(only here the hyphen denotes a character range).
Solution 2:
Escape the hyphen.
[a-zA-Z0-9!$* \t\r\n\-]
UPDATE:
Never mind this answer - you can add the hyphen to the group but you don't have to escape it. See Konrad Rudolph's answer instead which does a much better job of answering and explains why.
Solution 3:
It’s less confusing to always use an escaped hyphen, so that it doesn't have to be positionally dependent. That’s a \-
inside the bracketed character class.
But there’s something else to consider. Some of those enumerated characters should possibly be written differently. In some circumstances, they definitely should.
This comparison of regex flavors says that C♯ can use some of the simpler Unicode properties. If you’re dealing with Unicode, you should probably use the general category \p{L}
for all possible letters, and maybe \p{Nd}
for decimal numbers. Also, if you want to accomodate all that dash punctuation, not just HYPHEN-MINUS, you should use the \p{Pd}
property. You might also want to write that sequence of whitespace characters simply as \s
, assuming that’s not too general for you.
All together, that works out to apattern of [\p{L}\p{Nd}\p{Pd}!$*]
to match any one character from that set.
I’d likely use that anyway, even if I didn’t plan on dealing with the full Unicode set, because it’s a good habit to get into, and because these things often grow beyond their original parameters. Now when you lift it to use in other code, it will still work correctly. If you hard‐code all the characters, it won’t.
Solution 4:
[-a-z0-9]+,[a-z0-9-]+,[a-z-0-9]+ and also [a-z-0-9]+ all are same.The hyphen between two ranges considered as a symbol.And also [a-z0-9-+()]+ this regex allow hyphen.