如何使用正则表达式禁止连续的五位数和更多位数? [英] How to disallow consecutive five digits and more using regex?
问题描述
如果字符串包含连续的五位数字,我想禁止:12345、11111、123456.
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.
推荐答案
匹配5个连续数字的正则表达式为\d{5}
.
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.
所以整个正则表达式可以是:^(?!.*?\d{5}).+$
So the whole regex can be: ^(?!.*?\d{5}).+$
这篇关于如何使用正则表达式禁止连续的五位数和更多位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!