1

I'm learning RegEx, and I'm stuck in the following exercise:

I must match:

1 (555) 555-5555
5555555555
1 555-555-5555
555-555-5555

and not:

1 555)555-5555
(6505552368)
10 (757) 622-7382
555)-555-5555

My expression (not working) is:

/([0-9]? ?)?(([0-9]{3})|(\([0-9]{3}\)))( |\-)?\2\5?\2[0-9]/ig

Could you please help me? I can't figure out what's wrong...

Aminah Nuraini
  • 18,120
  • 8
  • 90
  • 108
Alby11
  • 607
  • 1
  • 7
  • 15

3 Answers3

1

You could come up with:

^\d\ *(?:\(\d+\))?[- \d]+$

See a demo on regex101.com.

Broken down:

^   - an anchor to bind the expression to the beginning of the line
\d  - one digit of 0-9
\ * - zero or more spaces
(?:\(\d+\))? - digits in parentheses, made optional
[- \d]+ - characters from the specified class
$ - bind the expression to the end 

But quoting from the regex tag:

Since regular expressions are not fully standardized, all questions with this tag should also include a tag specifying the applicable programming language or tool.

Please update your question and apply the used programming language.


As pointed out by @Aminah, the given regex has flaws which can be avoided by using lookaheads, e.g.:

^(?!.*-{2,})\d\ *(?:\(\d+\))?[- \d]+$

The (?!.*-{2,}) makes sure that there are no two consequent slashes allowd.

Jan
  • 42,290
  • 8
  • 54
  • 79
1

You can use this:

/^(\d? ?)?(\d{3}|\(\d{3}\))[ -]?\d{3}[ -]?\d+$/gm

Demo

Explanation:

  1. ^(\d? ?)?: ^ to match the very beginning of the string. \d is equal to [0-9]
  2. (\d{3}|\(\d{3}\)): It's to match the second group where brackets are optional. You were right, but you put too many unnecessary parentheses.
  3. [ -]?: It's equal to ( |-)?
  4. \d+$: $ is for the end of the string.
  5. /gm: m flag is for multiple lines
Aminah Nuraini
  • 18,120
  • 8
  • 90
  • 108
1

Ok this one is bit tricky, to test actually.

Here you go:

^(\d\s?(?:\(\d{3}\))?\s?[\d|\-]{8,12})$

This one catches the full numbers only and returns the complete number, not the partials like others mentioned in other answers.

Test here:

https://regex101.com/r/hI5vT2/2

Nabeel Khan
  • 3,715
  • 2
  • 24
  • 37