【问题标题】:How do you get all matches in a repeated backreference? [duplicate]您如何在重复的反向引用中获得所有匹配项? [复制]
【发布时间】:2018-05-25 14:29:46
【问题描述】:

带有测试字符串:

This is a string1 string2 string3 string4 string5 string6 string7 so it is.

是否可以将所有 stringX 作为反向引用?目前我尝试过的每次都会覆盖,所以我最终得到一场比赛 - 最后一场。

例如使用这样的正则表达式:

/This is a (?:(string\d) )+so it is./

最后总是会匹配到string7

到目前为止,我发现的最好的方法是删除上面的 ?: 并在空格上爆炸,但我想知道是否有办法完全使用正则表达式。

更新专门针对 PHP,实现此目的的最佳方法是什么?

【问题讨论】:

  • 不能用“正则表达式”完成,因为任何正则表达式都在代码中使用。你的是什么?请注意,获取所有 捕获 仅适用于几种语言。
  • 最小的例子是在 PHP 中使用 preg_match 和上面的 caluss,但我不想将它限制为一种语言。我想我可以指定 PCRE,但我实际上只是在询问正则表达式。
  • 味道/环境如何?
  • @Aran-Fey 啊,你是对的,我一直在寻找类似的答案,但失败了。我可能应该删除这个很好回答的问题。
  • 无需删除 - 您可以将自己的问题标记为该问题的副本。您的问题可以作为其他有相同问题的人的路标。

标签: php regex


【解决方案1】:

您可以通过 \G 使用此正则表达式:

(?:This is a|\G(?!\A))\h+((?=.*so it is\.)string\d+)
  • \G 断言位置在上一个匹配的结尾或第一个匹配的字符串的开头
  • (?!\A) 是否定前瞻断言我们在行开始时不匹配 \G
  • (?=.*so it is\.) 是肯定的超前断言我们在输入中的当前位置之前有so it is.

RegEx Demo

代码:

$re = '/(?:This is a|\G(?!\A))\h+((?=.*so it is\.)string\d+)/m';
$str = 'This is a string1 string2 string3 string4 string5 string6 string7 so it is.';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches[1]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2011-03-09
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 2023-03-15
    • 2013-05-06
    相关资源
    最近更新 更多