I'm trying to write a regular that will check for numbers, spaces, parentheses, + and - this is what I have so far:
/\d|\s|\-|\)|\(|\+/g
but im getting this error: unmatched ) in regular expression any suggestions will help. Thanks
I'm trying to write a regular that will check for numbers, spaces, parentheses, + and - this is what I have so far:
/\d|\s|\-|\)|\(|\+/g
but im getting this error: unmatched ) in regular expression any suggestions will help. Thanks
You need to escape your parenthesis, because parenthesis are used as special syntax in regular expressions:
instead of '(':
\(
instead of ')':
\)
Also, this won't work with '+' for the same reason:
\+
Edit: you may want to use a character class instead of the 'or' notation with '|' because it is more readable:
[\s\d()+-]
Use a character class:
/[\d\s()+-]/g
This matches a single character if it's a digit \d
, whitespace \s
, literal (
, literal )
, literal +
or literal -
. Putting -
last in a character class is an easy way to make it a literal -
; otherwise it may become a range definition metacharacter (e.g. [A-Z]
).
Generally speaking, instead of matching one character at a time as alternates (e.g. a|e|i|o|u
), it's much more readable to use a character class instead (e.g. [aeiou]
). It's more concise, more readable, and it naturally groups the characters together, so you can do e.g. [aeiou]+
to match a sequence of vowels.
Beginners sometimes mistake character class to match [a|e|i|o|u]
, or worse, [this|that]
. This is wrong. A character class by itself matches one and exactly one character from the input.
Here is an awesome Online Regular Expression Editor / Tester! Here is your solution there.