正则表达式没有按预期工作:' / =(\ w + \ s *)+ = /'

时间:2015-10-09 18:09:20

标签: php regex pcre

这就是我所拥有的:

<?php

preg_match_all('/=(\w+\s*)+=/', 'aaa =bbb ccc ddd eee= zzz', $match);
print_r($match);

仅匹配eee:

Array
(
    [0] => Array
        (
            [0] => =bbb ccc ddd eee=
        )

    [1] => Array
        (
            [0] => eee
        )

)

我需要它来匹配bbb,ccc,ddd,eee,例如:

...
   [1] => Array
        (
            [0] => bbb
            [1] => ccc
            [2] => ddd
            [3] => eee
        )
...

问题出在哪里?

4 个答案:

答案 0 :(得分:2)

试试这个正则表达式:

(\w+)(?=[^=]*=[^=]*$)

解释

(\w+)          # group all words
(?=            # only if right after can be found:
    [^=]*      # regardless of non '=' character
    =          # one '=' character
    [^=]*$     # non '=' character till the end makes sure the first words are eliminated... You can try remove it from regex101 to see what happens.
)

Regex live here.

希望它有所帮助。

答案 1 :(得分:1)

这是预期的行为。小组捕获在重复时被覆盖。

  

1组,1次捕获

您应该在每次尝试时匹配一个令牌,而不是尝试在1次匹配尝试中获取它们。使用\G匹配the end of last match

这样的事情应该有效:

/(?(?=^)[^=]*+=(?=.*=)|\G\s+)([^\s=]+)/

regex101 Demo

正则表达式细分

  • (?(?=^) ... | ... )如果在字符串的开头
    • [^=]*+=消费所有内容直到第一个=
    • (?=.*=)并检查是否还有结束=
  • ELSE
    • \G\s+仅匹配最后一场比赛在此处结束,消耗前面的空格
  • ([^\s=]+)匹配1,在第1组中捕获。

如果您对匹配多组令牌感兴趣,还需要匹配两组令牌中的文字:

/(?(?=^)[^=]*+=(?=.*=)|\G\s*+(?:=[^=]*+=(?=.*=))?)([^\s=]+)/

regex101 Demo

答案 2 :(得分:0)

您的正则表达式以=开头和结尾,因此唯一可能的匹配是:

=bbb ccc ddd eee=

答案 3 :(得分:0)

您可以将preg_replacepreg_split一起使用,即:

$string = "aaa =bbb ccc ddd eee= zzz";
$matches = preg_split('/ /',  preg_replace('/^.*?=|=.*?$/', '', $string));
print_r($matches);

<强>输出:

Array
(
    [0] => bbb
    [1] => ccc
    [2] => ddd
    [3] => eee
)

<强>样本:

http://ideone.com/pAmjbk