How to use regex to limit the total length of an input string

I have this regex and you want to add a rule that limits the total length to no more than 15 characters. I have seen several examples, but they are not entirely clear. Can you help me change this expression to support the new rule.

^([AZ]+( )*[AZ]+)+$ 
+6
source share
3 answers

Actually, all this can be simplified:

 ^[AZ][AZ ]{0,13}[AZ]$ 

does exactly what you want. Or at least what your current regex does (plus a length constraint). This especially helps to avoid problems with the catastrophic backtrackin g that you configure in order to enclose such quantifiers.

Example:

Try the line ABCDEFGHIJKLMNOP against the original source expression. The regex engine will match this instantly. Now try the line ABCDEFGHIJKLMNOPa . Regular expression will take nearly 230,000 steps to realize that it cannot match the string. And each additional character doubles the number of steps needed to determine a failed match.

+11
source

Since you mentioned this in the title, a negative look at your case would look like this:

 ^(?!.{16,})(regex goes here)+$ 

Note the negative lookahead at the beginning (?!.{16,}) , which checks that the string does not have 16 or more characters.

However, since @TimPietzcker pointed out that your Regex can be simplified and rewritten in a form that is not subject to backtracking, so you should use its solution.

+9
source
 ^(?=.{15}$)([AZ]+( )*[AZ]+)+$ 

Take a look

+5
source

Source: https://habr.com/ru/post/902230/


All Articles