简体   繁体   English

字符串必须与7位数字和可选的非连续字符匹配

[英]String must match 7 digits and optional non consecutive characters from set

I am trying to write a regex to match if it only contains [-+./()] and digits. 我试图写一个正则表达式来匹配,如果它只包含[-+。/()]和数字。 The non digits must not have two consecutive matches. 非数字不能连续两个匹配。 The string must also contain 7 digits in total. 该字符串也必须总共包含7位数字。

ie

  • (( is invalid. ((无效。
  • ( is also invalid (也是无效的
  • (1234567)+ is valid and (1234567)+有效,并且
  • ()1+34564+0 is also valid ()1+34564+0也有效

I've written this following regex: /^(([()/.+ -])\\1?(?!\\2)|\\d)*$/ 我已经用正则表达式写了这个:/ /^(([()/.+ -])\\1?(?!\\2)|\\d)*$/

The part that is not working for me is, the mandatory digits. 对我不起作用的部分是必需数字。 I am not sure how to complete the the regex. 我不确定如何完成正则表达式。 How should the regex look for the above rules? 正则表达式应如何查找上述规则?

You could use a lookahead to validate the presence of 7 digits : 您可以使用先行验证7位数字的存在:

(?=\D*(\d\D*){7}$)

Placed at the beginning of your regex, it will make sure the matched String contains exactly 7 digits. 将其放置在正则表达式的开头,以确保匹配的字符串正好包含7位数字。

As a whole regex, I would use ^(?=\\D*(\\d\\D*){7}$)(?:(?:([-()+./])(?!\\2))|\\d)* . 作为一个正则表达式,我将使用^(?=\\D*(\\d\\D*){7}$)(?:(?:([-()+./])(?!\\2))|\\d)* You can try it here . 您可以在这里尝试。

我认为这可以做到:

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

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

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