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

AustinTX picture AustinTX · Nov 23, 2011 · Viewed 8.3k times · Source

I have this regular expression and want to add the rule which limit the total length is no more than 15 chars. I saw some lookahead examples but they're not quite clear. Can you help me to modify this expression to support the new rule.

^([A-Z]+( )*[A-Z]+)+$

Answer

Rich O'Kelly picture Rich O'Kelly · Nov 23, 2011

Since you mentioned it in the title, a negative lookahead for your case would be:

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

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

However, as @TimPietzcker has pointed out your Regex can be simplified a lot, and re-written in such a form that is not prone to backtracking, so you should use his solution.