简体   繁体   中英

Regex - Prevent repeated characters

I've spent hours and hours trying to solve this.

Here is my Regex string:
^(?=.{4})(?!.{32})[a-zA-Z0-9_]+((\\.(-\\.)*-?|-(\\.-)*\\.?) [a-zA-Z0-9_]+)*$ -
You can test it here

Here is what I tried to acomplish (username validation):

  1. string length range -> OK
  2. letters, numbers, _ - . allowed (- and . disallowed at begining and or end of username) -> OK
  3. need to prevent repeated characters (over 5 characters in line) -> need help!

This:

^(?=.{4})(?!.{32})(?!.*(.)\1{4})\w[\w.-]+\w$

Use another (negative) lookahead to take care of the third condition. This one will make sure that there is no character, that is followed by itself 4 times.

I also simplified your character classes by using \\w which represents [a-zA-Z0-9] . Also, as FJ pointed out, you can combine the first two lookaheads into one:

^(?=.{4,31}$)(?!.*(.)\1{4})\w[\w.-]+\w$

Try the following:

^(?=.{4,31}$)(?![-.])(?:(?!(.)\1{4})[-.\w])+(?<![-.])$

Example: http://regexr.com?32ffq

This assumes that you actually meant prevent repeated characters, instead of permit.

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