如何使用正则表达式前瞻来限制输入字符串的总长度 [英] How to use regex lookahead to limit the total length of input string

查看:482
本文介绍了如何使用正则表达式前瞻来限制输入字符串的总长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正则表达式,想添加规则,限制总长度不超过15个字符。我看到了一些前瞻性的例子,但它们不是很清楚。你可以帮我修改这个表达式来支持新的规则。

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]+)+$


推荐答案

其实这一切都可以简化很多:

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.

案例:

尝试字符串 ABCDEFGHIJKLMNOP 反对您的原始正则表达式。正则表达式引擎将立即匹配。现在尝试字符串 ABCDEFGHIJKLMNOPa 。它将采用正则表达式引擎近似于230,000 步骤来找出它不能匹配字符串。每个附加字符将确定失败的匹配所需的步骤数量加倍。

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.

这篇关于如何使用正则表达式前瞻来限制输入字符串的总长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆