如何使用正则表达式前瞻来限制输入字符串的总长度
我有这个正则表达式,想要添加限制总长度不超过 15 个字符的规则。我看到了一些前瞻示例,但它们不太清楚。你能帮我修改这个表达式以支持新规则吗?
^([A-Z]+( )*[A-Z]+)+$
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]+)+$
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
既然您在标题中提到了它,那么您的情况的负前瞻将是:
注意开头的负前瞻
(?!.{16,})
,它检查字符串是否有 16或更多字符。然而,正如 @TimPietzcker 指出的那样,你的正则表达式可以被简化很多,并以不易回溯的形式重写,所以你应该使用他的解决方案。
Since you mentioned it in the title, a negative lookahead for your case would be:
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.
实际上,这一切都可以简化很多:
完全按照你想要的去做。或者至少是您当前的正则表达式的作用(加上长度限制)。这尤其可以避免您在嵌套量词时为自己设置的灾难性回溯问题像那样。
恰当的例子:
尝试针对原始正则表达式使用字符串
ABCDEFGHIJKLMNOP
。正则表达式引擎将立即匹配。现在尝试字符串ABCDEFGHIJKLMNOPa
。正则表达式引擎需要近 230,000 步才能发现它无法匹配该字符串。每增加一个字符,确定失败匹配所需的步骤数就会增加一倍。Actually, all this can be simplified a lot:
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 stringABCDEFGHIJKLMNOPa
. 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.查看
See it