Home > database >  Regex expression not following the given length
Regex expression not following the given length

Time:04-01

I have the regex as follow:

^[a-z|A-Z]((?!.*--).*[[:alnum:]]|[-]){1,22}[a-z|A-Z|0-9]$

For some reason, the length of the given string if set to 24 is still accepted. The original capture group needs to be: string between 3-24 alphanumeric characters, must begin with a letter, end with a letter or digit, and cannot contain consecutive hyphens.

Why is the regex not checking the quantifier of length 1-22 in the middle part?

CodePudding user response:

The main pattern should be just ^[a-z].{1,22}[a-z\d]$ to specify that the whole match must be 3-24 characters and have the required beginning and ending characters. You can use the case-insensitive modifier to make a-z match A-Z as well.

Then add a negative lookahead to prohibit .*--. The final result is:

^(?!.*--)[a-z].{1,22}[a-z\d]$

DEMO

  • Related