Search code examples
javascriptregexregex-lookaroundsregex-group

Javascript Regex Lookahead


I am not understanding why this regex pattern is not matching as expected. I am testing this pattern on https://regexr.com.

regex =/^1?\((?=\d{3}\))[-. ]?(\d{3})$/
sample = 1(123) 123

My understanding is first pattern should be number 1 or nothing then 3 digits in closed parentheses or no parentheses at all. There should not be open parentheses which will be the case when we only use (?(\d{3})\)? and after [-. ] which is optional, followed by 3 digits end.


Solution

  • I am not 100% sure I read your requirements correctly, but I think you want these scenarios to work?

    1(234) 567
    1(234)567
    (234) 567
    (234)567
    1234 567
    1234567
    234 567
    234567
    

    And, probably more trickily, you want the 3 matching groups to be the first digit if any, the 3 numbers inside the optional parenthesis, and then the final 3 numbers.

    This is my first attempt, using a look-ahead to check for the valid cases of with/without parenthesis, then following that with grabbing the two groups for the two sets of numbers.

    ^(1?)(?=\d{3}[-. \d]+|\(\d{3}\))\(?(\d{3})\)?[-. ]?(\d{3})$