Reputation: 105547
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}
Upvotes: 3
Views: 1947
Reputation: 627537
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 /i
modifier:
/^[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
Upvotes: 3
Reputation: 24019
I'm adding this in case you're limiting input field entry.
While not regex, I use this function and it works well (I will add that it's important to let the user know you're limiting the input length from UI/UX point of view):
limitLength: function(element, lengthOf){
var fieldLength = element.value.length;
if(fieldLength <= lengthOf){
return true;
} else {
var str = element.value;
str = str.substring(0, str.length - 1);
element.value = str;
}
}
Usage:
<input type="text" onInput="my.namespace.limitLength(this,39)">
Upvotes: 0
Reputation: 68443
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.
Upvotes: 1