如何使用正则表达式前瞻来限制输入字符串的总长度

发布于 2024-12-17 19:24:01 字数 126 浏览 8 评论 0原文

我有这个正则表达式,想要添加限制总长度不超过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

z祗昰~ 2024-12-24 19:24:01

既然您在标题中提到了它,那么您的情况的负前瞻将是:

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

注意开头的负前瞻 (?!.{16,}) ,它检查字符串是否有 16或更多字符。

然而,正如 @TimPietzcker 指出的那样,你的正则表达式可以被简化很多,并以不易回溯的形式重写,所以你应该使用他的解决方案。

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.

我很坚强 2024-12-24 19:24:01

实际上,这一切都可以简化很多:

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

完全按照你想要的去做。或者至少是您当前的正则表达式的作用(加上长度限制)。这尤其可以避免您在嵌套量词时为自己设置的灾难性回溯问题像那样。

恰当的例子:

尝试针对原始正则表达式使用字符串 ABCDEFGHIJKLMNOP 。正则表达式引擎将立即匹配。现在尝试字符串 ABCDEFGHIJKLMNOPa。正则表达式引擎需要近 230,000 步才能发现它无法匹配该字符串。每增加一个字符,确定失败匹配所需的步骤数就会增加一倍。

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.

兔小萌 2024-12-24 19:24:01
^(?=.{15}$)([A-Z]+( )*[A-Z]+)+$

查看

^(?=.{15}$)([A-Z]+( )*[A-Z]+)+$

See it

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文