How to disallow consecutive five digits and more using regex?

♀尐吖头ヾ 提交于 2020-01-30 13:08:22

问题


I would like to disallow if the string contains consecutive five digits and more like: 12345, 11111, 123456.

I have got success in disallowing any number in string using following regex:

/^[^0-9]+$/

I have created a sandbox demo. I want to disallow five consecutive numbers/digits. Currently it is disallowing any number.


回答1:


The regex matching 5 consecutive digits is \d{5}.

To disallow such a string (actually, even more consecutive digits), at any position in the source string, this regex should be put:

  • inside a negative lookup: (?!...),
  • after a regex matching any number (zero or more) of any chars .*? (reluctant variant).

After this negative lookup, there should be a regex matching the whole string: .+ (I assume that you are not interested in an empty string, so I put +, not *).

The whole regex above should be preceded with ^ and followed with $ anchors.

So the whole regex can be: ^(?!.*?\d{5}).+$




回答2:


This is a good website for testing your regex:

https://regex101.com/

You could try this:

/^[0-9]{5,}$/

5 numbers or more will pass the regex.



来源:https://stackoverflow.com/questions/50813606/how-to-disallow-consecutive-five-digits-and-more-using-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!