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

后端 未结 3 1719
离开以前
离开以前 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:15

    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.

提交回复
热议问题