Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression limit string size

Tags:

How to limit string size for this regular expression?

/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/

I just need to add the quantifier {3,16}.

like image 622
user558134 Avatar asked Jun 25 '12 21:06

user558134


People also ask

How do you restrict length in regex?

The ‹ ^ › and ‹ $ › anchors ensure that the regex matches the entire subject string; otherwise, it could match 10 characters within longer text. The ‹ [A-Z] › character class matches any single uppercase character from A to Z, and the interval quantifier ‹ {1,10} › repeats the character class from 1 to 10 times.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What is a string limit?

While an individual quoted string cannot be longer than 2048 bytes, a string literal of roughly 65535 bytes can be constructed by concatenating strings.

How do you limit the length of a string in Java?

The indexing is done within the maximum range. It means that we cannot store the 2147483648th character. Therefore, the maximum length of String in Java is 0 to 2147483647. So, we can have a String with the length of 2,147,483,647 characters, theoretically.


1 Answers

Sprinkle in some positive lookahead to test for the total length of the string by adding

(?=.{3,16}$)

at the start of the regex. The final regex is then:

/^(?=.{3,16}$)[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/
like image 63
buckley Avatar answered Oct 06 '22 00:10

buckley