正则表达式 PCRE:验证不包含 3 个或更多连续数字的字符串
我搜索了这些问题但找不到答案。我需要一种与 php preg_match 函数一起使用的模式,仅匹配不包含 3 个或更多连续数字的字符串,例如:
rrfefzef => TRUE
rrfef12ze1 => TRUE
rrfef1zef1 => TRUE
rrf12efzef231 => FALSE
rrf2341efzef231 => FALSE
到目前为止,我已经编写了以下正则表达式:
@^\D*(\d{0,2})?\D*$@
它仅匹配仅出现一次 \d{0,2}
如果其他人有时间帮助我解决此问题,我将不胜感激:)
问候,
I've searched the questions but can't find an answer. I need a pattern that, used with php preg_match function, only match strings that does not contains 3 or more consecutive digits, e.g.:
rrfefzef => TRUE
rrfef12ze1 => TRUE
rrfef1zef1 => TRUE
rrf12efzef231 => FALSE
rrf2341efzef231 => FALSE
So far, I have wrote the following regex:
@^\D*(\d{0,2})?\D*$@
it only match the strings that have only one occurrence of \d{0,2}
If someone else has time to help me with this, I would appreciate it :)
Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果字符串有两个或多个连续数字,则拒绝该字符串:
\d{2,}
或者仅在没有连续数字时才使用负向前查找来匹配:
^(?!.*\d {2}).*$
Reject the string if it has two or more consecutive digits:
\d{2,}
Or use negative lookahead to match only if there are no consecutive digits:
^(?!.*\d{2}).*$
匹配后面不跟三位数字的所有字符。 示例。
Matches all characters that are not followed by three digits. Example.
您可以搜索
\d\d
,它将匹配所有错误字符串。然后您可以调整进一步的程序逻辑以对此做出正确的反应。如果您确实需要对包含相邻数字的字符串进行“正向”匹配,那么这也应该有效:
You could search for
\d\d
, which will match on all the bad strings. Then you can adjust your further program logic to correctly react to that.If you really need a "positive" match on strings that contain adjacent digits, this should also work:
是否有什么因素阻止您简单地在
preg_match()
函数前添加“!”前缀,从而反转布尔结果?是不是容易多了...
Is there anything stopping you from simply prefixing the
preg_match()
function with "!", thereby reversing the boolean result?Is so much easier...
如果我正确解释您的要求,则以下正则表达式将匹配您的有效输入,而不匹配无效输入。
解释如下
If I interprete your requirement correct, following regex matches your valid inputs without matching the invalid inputs.
is explained as follows