子表达式(正则表达式)的无限匹配只返回一个匹配 [英] Infinite matching of a subexpressions (regular expressions) returns only one match

查看:46
本文介绍了子表达式(正则表达式)的无限匹配只返回一个匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的正则表达式(非常简化):

I have a regular expression like this (much simplified):

^(ab)*$

并且与此匹配:

abababababababab

当我通过 preg_match 运行它时:

When I run it through preg_match:

preg_match('/$(ab)*$/', 'abababababababab', $matches);
print_r($matches);

我明白了:

Array
(
    [0] => abababababababab
    [1] => ab
)

虽然我希望这样:

Array
(
    [0] => abababababababab
    [1] => ab
    [2] => ab
    [3] => ab
    [4] => ab
    [5] => ab
    [6] => ab
    [7] => ab
    [8] => ab
}

我怎样才能得到我所期望的?

How can I get what I expect?

(请注意,子表达式可能更复杂,例如 ([aA][bB]),我希望匹配的表达式按主题中的顺序排列.)

(Note that the subexpression could be more complicated, e.g. ([aA][bB]), and I want the matched expressions in their order in the subject.)

推荐答案

使用 preg_match_all 这样做:

preg_match_all('/(ab)/', 'abababababababab', $matches);
print_r($matches);

请记住,preg_match 仅提供第一个匹配项,而 preg_match_all 具有相同的功能,但返回所有匹配项.另请注意,现在正则表达式已更改.如果您使用星号,它可能会在第一次匹配时消耗整个字符串.但是,您可以尝试使用诸如 (ab)*? 之类的方法来使其非贪婪.

Remember that preg_match only provides the first match and that preg_match_all has the same functionality, but returns all. Also note that now the regular expression has changed. If you use the asterisk, it'll likely consume the entire string on the first match. You could, however, try something like (ab)*? to make it nongreedy.

这篇关于子表达式(正则表达式)的无限匹配只返回一个匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆