I’ve got the following Regex check, which makes sure that only letters, numbers and * characters are input.
Regex.IsMatch(searchString, @"^[a-zA-Z0-9*]+$")
However, I’d like to extend it to also accept ( ) [ ] characters too. This is what I’ve tried so far, but it’s returning false:
Regex.IsMatch(searchString, @"^[a-zA-Z0-9[]()*]+$")
Could anyone suggest a solution?
Escape them with
\:Should be noted that the escaping rules are different depending on whether the character is inside a character class (i.e.
[_chars_]) or not.For example –
(must be escaped to\(outside of a character class, because otherwise it denotes the start of a group (i.e.(_something to capture_)). Other characters like?and.must always be escaped if outside a character class.Note
I’ve edited out the use of the term ‘character group‘ because it’s been rightly pointed out to me that, however clearly I try to delineate, it can still cause confusion with a ‘group’ (capturing/non-capturing). Regex can be confusing enough as it is without me muddying the waters further.