简体   繁体   中英

python regex: don't allow a specific character to repeat

I have a regex

^[a-z][a-z0-9\-]{6,10}[a-z0-9]$

Which matches the following rules:

  • 8-12 characters in length
  • first character is lowercase alpha
  • last characters lowercase alpha or digit
  • internal characters can contain a hyphen

it's re-used a lot in a module, always alongside some other rules and regexes

while writing out some unit tests, i noticed that it's always used in conjunction with another specific rule.

  • hyphens may not repeat

i can't wrap my head around integrating that rule into this one. i've tried a few dozen approaches with lookbehinds and lookaheads, but have had no luck on isolating to the specific character AND keeping the length requirement.

No repeating hyphen ^[az](?:[a-z0-9]|-(?!-)){6,10}[a-z0-9]$

Explained

 ^ [a-z] 
 (?:
      [a-z0-9]   # alnum
   |             # or
      - (?! - )  # hyphen if not followed by hyphen
 ){6,10}
 [a-z0-9] $

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