views:

71

answers:

4

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

A: 

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()+-]

orangeoctopus
+6  A: 

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.

References


Caveat

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.

Related questions

polygenelubricants
A: 

Try this:

[\d\s-+()]
bits
Although `-` is placed directly after the short hand character class `\s` and therefor needs no escaping, I'd opt to put it (un-escaped) at the start or end of the character class to not cause confusion: `[-\d\s+()]` or `[\d\s+()-]`.
Bart Kiers
A: 

Here is an awesome Online Regular Expression Editor / Tester! Here is your solution there.

fuzzy lollipop