1

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.

3
  • 1
    You could add another test to see that it doesn't match "--" like: and not "--" in somestring Commented May 5, 2017 at 17:45
  • 2
    Don't try and put too much logic inside a regex. Just define a function that applies the first regex and then check for double hyphens afterwards. Commented May 5, 2017 at 17:46
  • That is how things are currently working. Unfortunately, someone inevitably invokes this regex instead of the combined function, and bad data gets through. I've had to do a dozen cleanups. Commented May 5, 2017 at 18:02

1 Answer 1

7

No repeating hyphen ^[a-z](?:[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] $
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a ton. i never thought of using the | like that! I kept trying to work with something like [a-z0-9]+[a-z0-9\-] and trying to apply limits around that.
@JonathanVanasco - No problem. Sometimes all you have to do is read out loud what a construct is. For classes, it's like a or b or c. The or is really alternations. So, you could always split them out into alternations without losing meaning. Once split out, the can be operated on independently (ie. qualified).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.