How to disallow consecutive five digits and more using regex?

后端 未结 2 1882
栀梦
栀梦 2021-01-29 06:58

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

2条回答
  •  被撕碎了的回忆
    2021-01-29 07:26

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

提交回复
热议问题