简体   繁体   English

如何使用正则表达式匹配此字符串?

[英]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: 使用OR来匹配以下两种情况之一:

\(\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 ) : 您可以使用条件构造 :捕获一个可选的开头(然后匹配3位数字,然后检查Group 1是否为空,如果不是,则匹配结束)

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

See the regex demo . 参见regex演示 Add anchors/boundaries as per requirements. 根据要求添加锚点/边界。

Details 细节

  • (\\()? - An optional capturing group 1 matching a ( char (\\()? -与( char
  • \\d{3} - 3 digits \\d{3} -3位数字
  • (?(1)\\)) - If Group 1 matched, match a ) (?(1)\\)) -如果第1组相匹配,匹配一个)
  • \\d{7} - 7 digits. \\d{7} -7位数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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