【问题标题】:Get regex to match multiple instances of the same pattern获取正则表达式以匹配同一模式的多个实例
【发布时间】:2019-07-30 11:59:48
【问题描述】:

所以我有这个正则表达式 - regex101:

\[shortcode ([^ ]*)(?:[ ]?([^ ]*)="([^"]*)")*\]

试图匹配这个字符串

[shortcode contact param1="test 2" param2="test1"]

现在,正则表达式匹配这个:

[contact, param2, test1]

我希望它匹配这个:

[contact, param1, test 2, param2, test1]

如何让正则表达式匹配参数模式的第一个实例,而不仅仅是最后一个?

【问题讨论】:

  • @WiktorStribiżew 那么,如果我要为此使用 PHP,我想要的东西是不可能的?
  • 可能,有两个正则表达式,如this,然后是this one。或者使用类似(?:\G(?!^)\s+|\[shortcode\s+(\S+)\s+)(\S+)="([^"]*)" (demo)
  • @WiktorStribiżew 这很有魅力,谢谢!如果您将其发布为答案,我可以确认。
  • @WiktorStribiżew 使用您提供的其他正则表达式,然后使用一些 PHP 进一步解析结果。

标签: regex


【解决方案1】:

你可以使用

'~(?:\G(?!^)\s+|\[shortcode\s+(\S+)\s+)([^\s=]+)="([^"]*)"~'

regex demo

详情

  • (?:\G(?!^)\s+|\[shortcode\s+(\S+)\s+) - 前一场比赛的结尾和 1+ 个空格紧跟在 (\G(?!^)\s+) 或 (|) 之后
    • \[shortcode - 文字字符串
    • \s+ - 1+ 个空格
    • (\S+) - 第 1 组:一个或多个非空白字符
    • \s+ - 1+ 个空格
  • ([^\s=]+) - 第 2 组:除空格和 = 之外的 1+ 个字符
  • =" - 文字子字符串
  • ([^"]*) - 第 3 组:除 " 之外的任何 0+ 个字符
  • " - " 字符。

PHP demo

$re = '~(?:\G(?!^)\s+|\[shortcode\s+(\S+)\s+)([^\s=]+)="([^"]*)"~';
$str = '[shortcode contact param1="test 2" param2="test1"]';
$res = [];
if (preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0)) {
    foreach ($matches as $m) {
        array_shift($m);
        $res = array_merge($res, array_filter($m));
    }
}
print_r($res);
// => Array( [0] => contact [1] => param1  [2] => test 2 [3] => param2  [4] => test1 )

【讨论】:

    【解决方案2】:

    尝试使用下面的正则表达式。

    regex101

    以下是您的用例,

    var testString = '[shortcode contact param1="test 2" param2="test1"]';

    var 正则表达式 = /[\w\s]+(?=[\="]|\")/gm;

    var found = paragraph.match(regex);

    如果您记录 found,您将看到结果为

    ["简码联系人 param1", "test 2", "param2", "test1"]

    只有在 ="" 之后,正则表达式才会匹配所有字母数字字符,包括下划线和空格。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2022-11-16
      • 2022-10-02
      • 1970-01-01
      • 2016-08-30
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多