使用php pre_match找到不相等字符的连续块



我有一个可变长度的字符串,例如" 0"one_answers" 1"字符,例如:" 1101"

我想检查是否存在一个以上的" 1"s。

的连续块

我正在使用php的preg_match函数

一些示例:

"0000" no matches
"1100" no matches
"1101" match

您可以建议正则表达式吗?

您可以在不使用正则表达式的情况下进行操作:

if ( strpos(trim($str, '0'), '0') ) { //...

,或者您还需要检查字符串仅包含0和1:

if ( count_chars(trim($str, '0'), 3) == '01' ) { //...

这两个测试的想法是相同的:trim函数在边界处删除了所有零,第二个功能证明至少有一个剩余零(1s之间的囚犯(。

也可以使用preg_match

完成
if ( preg_match('~10+1~', $str) ) { //...

,或者如果要检查所有字符串:

if ( preg_match('~^0*1+0+1[01]*$~D', $str) ) { //...

(d修改器强制$仅与字符串的末端匹配,而在尾随新线之前不匹配最后一行的末端。(

您可以使用类似的东西:

0*(?:1+0+1+)+[01]*

说明:

0* Matches 0 to n "0"
(?: Starts a non-matching group
1+ Matches at least one "1"
0+ Matches at least one "0"
1+ Matches at least one "1"
)+ Matches at least one of the group
[01]* Matches any left-over digits

这将适用于您的示例,以及:

010111001011 Matches
100101 Matches
0111001 Matches
1110 Doesn't match
001100000 Doesn't match

我认为您需要这样的东西:

/^1+0+[01]*1+$/
That means:
^1+: Starts with at least one "1"
0+: Followed by at least one "0"
[01]*: could contain a variable number of "0" or "1" 
1+$: Has to end with at least one "1"
This matches:
1011
1101
This does not match:
0000
1111
1100

如果不需要以" 1"结尾,这将适合:

/^1+0+1+[01]*$/
This matches:
1011
1101
11010
10110
This does not match:
0000
1111
1100

或那个:

/^((1+0+1)|(0+1+0+))+[01]*$/
This matches:
1011
1101
11010
10110
01000
00010
This does not match:
0000
1111
1100
01111
00011

最新更新