Search code examples
c#regexstring-matchingparentheses

How to match this string use Regex?


I have two string:

(123)4567890
1234567890

The pair ( and ) must both present, or both omit. Currently I use this Regex:

(?:(?:\(\d{3}\))|(?:\d{3}))\d{7}

which use OR to match one of two case:

\(\d{3}\)
\d{3}

Just for curious, how can I check for last match (have ( or not) in current match (check for ))? Can you suggest me another way to achieve same result?


Solution

  • You may use a conditional construct: capture an optional opening ( and then match 3 digits, and then check if Group 1 is empty, and if not, match the closing ):

    (\()?\d{3}(?(1)\))\d{7}
    

    See the regex demo. Add anchors/boundaries as per requirements.

    Details

    • (\()? - An optional capturing group 1 matching a ( char
    • \d{3} - 3 digits
    • (?(1)\)) - If Group 1 matched, match a )
    • \d{7} - 7 digits.