且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用正则表达式禁止连续的五位数和更多位数?

更新时间:2023-02-10 22:57:08

匹配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}).+$