我搜索了这些问题,却找不到答案。我需要一个与php preg_match函数一起使用的模式,只匹配不包含3个或更多连续数字的字符串,例如:
rrfefzef => TRUE
rrfef12ze1 => TRUE
rrfef1zef1 => TRUE
rrf12efzef231 => FALSE
rrf2341efzef231 => FALSE
到目前为止,我已经写了以下正则表达式:
@^\D*(\d{0,2})?\D*$@
它只匹配只出现一次\d{0,2}
如果其他人有时间帮助我,我会很感激:)
此致
答案 0 :(得分:1)
如果字符串有两个或多个连续数字,则拒绝该字符串:\d{2,}
或者只有在没有连续数字时才使用否定前瞻匹配:^(?!.*\d{2}).*$
答案 1 :(得分:0)
/^(.(?!\d\d\d))+$/
匹配所有未跟随三位数的字符。 Example
答案 2 :(得分:0)
您可以搜索\d\d
,它将匹配所有错误的字符串。然后你可以调整你的进一步程序逻辑以正确地做出反应。
如果你真的需要对包含相邻数字的字符串进行“肯定”匹配,那么这也应该有效:
^\D?(\d?\D)*$
答案 3 :(得分:0)
有没有什么可以阻止你简单地在preg_match()
函数前加上“!”,从而反转布尔结果?
!preg_match( '/\d{2,}/' , $subject );
更容易......
答案 4 :(得分:0)
如果我正确解释您的要求,则跟随正则表达式匹配您的有效输入而不匹配无效输入。
^\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) «$»