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 for some reason it is still letting me enter numbers
^[a-zA-Z -,.()]*$
any help would be great! Thanks.
There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.
You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".
If you wish to use a regex constraint on a number in a text type question, make sure you always have the value numbers under the appearance column. This restricts the display of alphabets, making only numbers visible for inputs.
The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).
-
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With