Reputation: 169
I have the simple regex @"[a-zA-Z]" to match all characters a-z in a string but I also need math operators (*, /, +, -). I was reading over the documentation on msdn but I got lost relatively fast due to the math operators being used as other tokens in the regex
This solution works:
@"[A-Za-z\*\+\-\/]"
Thanks for the help and resources everyone.
Upvotes: 3
Views: 3388
Reputation: 626802
The correct answer is
@"[A-Za-z*+/-]"
Or @"[A-Za-z-*+/]"
, or @"[-A-Za-z*+/]"
, or @"[A-Za-z*\-+/]"
.
Or, shorten it with a case-insensitive modifier: @"(?i)[A-Z*+/-]"
(or use a corresponding RegexOptions.IgnoreCase
with @"[A-Z*+/-]"
since it seems you are using C#).
Inside a character class, the unescaped hyphen should either be at the start or final position to be treated as a literal, or right after a range or shorthand class. Otherwise, it must be escaped. Also, ]
must be escaped if not at the beginning of the character class. Other characters do not have to be escpaed inside a character class.
To test, use an appropriate online regex tester. You need one for .NET, see Regex demo at RegexStorm.
Upvotes: 3