简体   繁体   中英

validate string data using regex which not allowed more than 3 same characters

Requirement is : Field is made of alpha characters and numbers, we not allow same character repeated more than 3 times continuously

Regex: ^([0-9A-Z])(?!\\1+$)[0-9A-Z]$

the above reg ex validate and not allow if the same charater repeated but we need to validate only more than 3 times repeated consinutly

ex: 1AAA23 -- Allowed
    2AAAA34 -- Not Allowed as 'A' repeated more tha 3 times
    22A22B5 -- Allowed 
    A222256 -- Not allowed as '2' repeated more than 3 times
    VN00000 -- Not allowed 
    111123 -- Not allowed
    1111AA -- Not allowed
    111AAA -- Allowed

The pattern that you tried only match 2 characters in total, and those characters can not be the same.

You can write the pattern like:

^(?!.*([A-Z0-9])\1{3})[A-Z0-9]+$
  • ^ Start of string
  • (?! Negative lookahead, assert that to the right is not
    • .*([A-Z0-9])\1{3} Optionally match any char and then capture 1 or chars A-Z0-9 in group 1 followed by matching that same char 3 times
  • ) Close lookahead
  • [A-Z0-9]+ Match 1+ repetitions of chars A-Z0-9
  • $ End of string

Regex demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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