开发者

Trying to write a regex that matches only numbers,spaces,parentheses,+ and -

开发者 https://www.devze.com 2023-01-07 04:54 出处:网络
I\'m trying to write a regular that will check for numbers, spaces, parentheses, + and - 开发者_运维知识库this is what I have so far:

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


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

  • regular-expressions.info/Character Class

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

  • Regex: why doesn’t [01-12] range work as expected?


Here is an awesome Online Regular Expression Editor / Tester! Here is your [\d\s()+-] there.


/^[\d\s\(\)\-]+$/

This expression matches only digits, parentheses, white spaces, and minus signs. example:

  • 888-111-2222
  • 888 111 2222
  • 8881112222
  • (888)111-2222
  • ...


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


Try this:

[\d\s-+()]
0

精彩评论

暂无评论...
验证码 换一张
取 消