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}
.
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.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
While an individual quoted string cannot be longer than 2048 bytes, a string literal of roughly 65535 bytes can be constructed by concatenating strings.
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.
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]+)*$/
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