I am attempting to create a regex that only allows letters upper or lowercase, and the characters of space, \'-\', \',\' \'.\', \'(\', and \')\'. This is what I have so far but
-
is special in character class. It is used to define a range as you've done with a-z
.
To match a literal -
you need to either escape it or place it such that it'll not function as range operator:
^[a-zA-Z \-,.()]*$
^^ escaping \
or
^[-a-zA-Z ,.()]*$
^ placing it at the beginning.
or
^[a-zA-Z -,.()-]*$
^ placing it at the end.
and interestingly
^[a-z-A-Z -,.()]*$
^ placing in the middle of two ranges.
In the final case -
is place between a-z
and A-Z
since both the characters surrounding the -
(the one which we want to treat literally) that is z
and A
are already involved in ranges, the -
is treated literally again.
Of all the mentioned methods, the escaping method is recommended as it makes your code easier to read and understand. Anyone seeing the \
would expect that an escape is intended. Placing the -
at the beginning(end) will create problems if you later add a character before(after) it in the character class without escaping the -
thus forming a range.