0

I was making a regular expression which can have the phone number of any length and can have the ( + and ) anywhere in the number.

^[\s()+-]*([0-9][\s()+-]*){6,20}$

But this regular expression is taking the spaces in it which is not correct. can someone help me to change this?

vaibhav
  • 762
  • 2
  • 12
  • 34
  • You do not want spaces, so remove `\s` whitespace shorthand character class. I also think you need to replace `*` (zero or more) with `?` (one or zero). – Wiktor Stribiżew Feb 22 '16 at 09:41

1 Answers1

0

Remove character class \s from regex pattern to avoid matching whitespaces. Also escape parentheses () with backslashes as they are metacharacters:

^[()+-]*([0-9][()+-]*){6,20}$
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • One does not have to escape parentheses inside a character class. – Wiktor Stribiżew Feb 22 '16 at 09:43
  • [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Writing_a_regular_expression_pattern): *Special characters like the dot(`.`) and asterisk (`*`) are not special inside a character set, so they don't need to be escaped.* Parentheses are one of those characters. – Wiktor Stribiżew Feb 22 '16 at 09:49
  • Also, see [*Metacharacters Inside Character Classes*](http://www.regular-expressions.info/charclass.html#special): *The only special characters or metacharacters inside a character class are the closing bracket (`]`), the backslash (``\``), the caret (`^`), and the hyphen (`-`). The usual metacharacters are normal characters inside a character class, and do not need to be escaped by a backslash.* – Wiktor Stribiżew Feb 22 '16 at 09:52
  • I would agree with your second link (http://www.regular-expressions.info/). But the first one has bad description: they said `Special characters like the dot(.) and asterisk (*) are not special inside a character set`. But special characters in regexp are: `\n, \r, \t, \v, \f, \xxx, \xhh` and metacharacters are: `^ { . * ( ) < > ? $ \ | [ +` – RomanPerekhrest Feb 22 '16 at 09:59