2010-10-18 23 views
0

我已经搜索了问题,但找不到答案。我需要的是,使用PHP的preg_match功能使用的模式,只匹配不包含3个或更多的连续数字的字符串,如:正则表达式PCRE:验证不包含3个或更多连续数字的字符串

rrfefzef  => TRUE 
rrfef12ze1  => TRUE 
rrfef1zef1  => TRUE 
rrf12efzef231 => FALSE 
rrf2341efzef231 => FALSE 

到目前为止,我已经写了下面的正则表达式:

@^\D*(\d{0,2})?\D*[email protected] 

只匹配有\d{0,2}

如果有人有时间来帮助我这个只会出现在一个字符串,我将不胜感激:)

Regards,

+2

你的第二个例子是错误的,不是吗? – 2010-10-18 13:16:16

+1

@GáborLipták:他只想检查连续的数字,以便正确评估。 – poke 2010-10-18 13:17:53

+2

难道你不能通过搜索'/ \ d {2,} /'真正简化这个并且否定结果吗? – thetaiko 2010-10-18 13:18:34

回答

0
/^(.(?!\d\d\d))+$/ 

匹配所有不跟随三位数的字符。 Example

+0

非常感谢,它工作正常! :) – garmr 2010-10-18 13:24:25

0

您可以搜索\d\d,它将匹配所有不良字符串。然后你可以调整你的进一步的程序逻辑,以正确地做出反应。

如果你真的需要在包含相邻数字串“正”的比赛,这也应该工作:

^\D?(\d?\D)*$ 
0

有什么阻止你只需添加前缀preg_match()功能与“!”从而颠倒布尔结果?

!preg_match('/\d{2,}/' , $subject); 

是如此容易得多......

+0

取决于我们是考虑他的测试用例还是他的书面规范 - 它满足“_...不包含2个或更多连续digits_”,但测试用例似乎是3或更多。然后,再次查看测试用例,他可能意味着3个或更多_sequential_ digits(即“** 123 **”= True,但“** 134 **”= False)。 – 2010-10-18 13:24:59

+0

事实上,我正在使用一个框架,在这种情况下,封装preg_match返回,所以我不能只是反向preg_match结果。我可以使用回调,但我更喜欢正则表达式的方法;) – garmr 2010-10-18 13:52:58

0

如果我interprete您的要求是正确的,下面的正则表达式没有匹配的无效输入相匹配的有效输入。

^\D*\d*\D*\d?(?!\d+)$ 

解释如下

> # ^\D*\d*\D*\d?(?!\d+)$ 
> # 
> # Options: case insensitive;^and $ match at line breaks 
> # 
> # Assert position at the beginning of a line (at beginning of the string or 
> after a line break character) «^» 
> # Match a single character that is not a digit 0..9 «\D*» 
> # Between zero and unlimited times, as many times as possible, giving back 
> as needed (greedy) «*» 
> # Match a single digit 0..9 «\d*» 
> # Between zero and unlimited times, as many times as possible, giving back 
> as needed (greedy) «*» 
> # Match a single character that is not a digit 0..9 «\D*» 
> # Between zero and unlimited times, as many times as possible, giving back 
> as needed (greedy) «*» 
> # Match a single digit 0..9 «\d?» 
> # Between zero and one times, as many times as possible, giving back as 
> needed (greedy) «?» 
> # Assert that it is impossible to match the regex below starting at this 
> position (negative lookahead) 
> «(?!\d+)» 
> # Match a single digit 0..9 «\d+» 
> #  Between one and unlimited times, as many times as possible, 
> giving back as needed (greedy) «+» 
> # Assert position at the end of a line (at the end of the string or before a 
> line break character) «$» 
1

拒绝的字符串,如果有两个或更多的连续数字:\d{2,}

或者使用负向前查找只匹配,如果没有连续的数字:^(?!.*\d{2}).*$

相关问题