简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM