2010-10-18 22 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}).*$

相關問題