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

后端 未结 3 1674
离开以前
离开以前 2021-01-05 04:54

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. Ca

3条回答
  •  礼貌的吻别
    2021-01-05 05:29

    Actually, all this can be simplified a lot:

    ^[A-Z][A-Z ]{0,13}[A-Z]$
    

    does exactly what you want. Or at least what your current regex does (plus the length restriction). This especially avoids problems with catastrophic backtracking which you're setting yourself up for when nesting quantifiers like that.

    Case in point:

    Try the string ABCDEFGHIJKLMNOP against your original regex. The regex engine will match that instantly. Now try the string ABCDEFGHIJKLMNOPa. It will take the regex engine nearly 230,000 steps to figure out it can't match the string. And each additional character doubles the number of steps needed to determine a failed match.

提交回复
热议问题