How to rewrite the [a-zA-Z0-9!$* \\t\\r\\n]
pattern to match hyphen along with the existing characters ?
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.