I have the following regex:
^[a-zA-Z_][\-_a-zA-Z0-9]*
I need to limit it's length to 39 characters. I tried the following but it didn't work:
^[a-zA-Z_][\-_a-zA-Z0-9]*{,38}
You just need to use a limited quantifier {0,38} and an end of string anchor $:
^[a-zA-Z_][-_a-zA-Z0-9]{0,38}$
^^^^^ ^
The syntax for the limited quantifiers is {min,max} where the max parameter is optional, but the minimum should be present. Without $ you may match 39 first characters in a much longer string.
You do not have to escape a hyphen when it is placed at the beginning of a character class (thus, I suggest removing it).
Also, you can further shorten the regex with an /imodifier:
/^[a-z_][-_a-z0-9]{0,38}$/i
or even
/^[a-z_][-\w]{0,38}$/i
Regarding the question from the comment:
wouldn't also that version work
(^[a-zA-Z_][-_a-zA-Z0-9]){0,39}$with 39 characters limit?
The regex matches
(^[a-zA-Z_][-_a-zA-Z0-9]){0,39} - 0 to 39 sequences of...
^ - start of the string[a-zA-Z_] - a single character from the specified range[-_a-zA-Z0-9] - a single character from the specified range $ - end of stringSo, you require a match to include sequences from the start of the string. Note a start of string can be matched only once. As you let the number of such sequences to be 0, you only match either the location at the end of the string or a 2 character string like A-.
Let's see what the regex does with the Word input. It mathces the start of string with ^, then W with [a-zA-Z_], then o with [-_a-zA-Z0-9]. Then the group ends, and that equals to matching the group once. Since we can match more sequences, the regex tries to match r with ^. It fails. So, the next position is retried and failed the same way, because d is not the ^ (start of string). And that way the end of string is matched because there is a 0 occurrences of ^[a-zA-Z_][-_a-zA-Z0-9] and there is an end of string $.
See regex demo
try
^[a-zA-Z_][\-_a-zA-Z0-9]{0,38}$
[0,38] means that number of instances of characters matching [\-_a-zA-Z0-9] could be 0 to 38.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With