简体   繁体   English

获取正则表达式以匹配同一模式的多个实例

[英]Get regex to match multiple instances of the same pattern

So I have this regex - regex101 : 所以我有这个正则表达式-regex101

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

Trying to match on this string 尝试匹配此字符串

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

Right now, the regex matches this: 现在,正则表达式与此匹配:

[contact, param2, test1]

I would like it to match this: 我希望它符合以下要求:

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

How can I get regex to match the first instance of the parameters pattern, rather than just the last? 如何获得正则表达式以匹配参数模式的第一个实例,而不仅仅是最后一个?

Try using the below regex. 尝试使用以下正则表达式。

regex101 regex101

Below is your use case, 以下是您的用例,

var testString = '[shortcode contact param1="test 2" param2="test1"]'; var testString ='[简码联系人参数1 =“测试2”参数2 =“测试1”]';

var regex = /[\\w\\s]+(?=[\\="]|\\")/gm; var regex = / [\\ w \\ s] +(?= [\\ =“] | \\”)/ gm;

var found = paragraph.match(regex); 找到的var = paragraph.match(regex);

If you log found you will see the result as 如果找到日志,您将看到以下结果:

["shortcode contact param1", "test 2", " param2", "test1"] [“ shortcode contact param1”,“ test 2”,“ param2”,“ test1”]

The regex will match all the alphanumeric character including the underscore and blank spaces only if they are followed by =" or " . 仅当后跟=“”时 ,正则表达式才匹配所有字母数字字符,包括下划线和空格。

I hope this helps. 我希望这有帮助。

You may use 您可以使用

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

See the regex demo 正则表达式演示

Details 细节

  • (?:\\G(?!^)\\s+|\\[shortcode\\s+(\\S+)\\s+) - either the end of the previous match and 1+ whitespaces right after ( \\G(?!^)\\s+ ) or ( | ) (?:\\G(?!^)\\s+|\\[shortcode\\s+(\\S+)\\s+) -前一个匹配的结尾和紧随其后的1+空格( \\G(?!^)\\s+ )或( |
    • \\[shortcode - literal string \\[shortcode -文字字符串
    • \\s+ - 1+ whitespaces \\s+ -1+空格
    • (\\S+) - Group 1: one or more non-whitespace chars (\\S+) -第1组:一个或多个非空白字符
    • \\s+ - 1+ whitespaces \\s+ -1+空格
  • ([^\\s=]+) - Group 2: 1+ chars other than whitespace and = ([^\\s=]+) -组2:1个除空格以外的字符, =
  • =" - a literal substring =" -文字子字符串
  • ([^"]*) - Group 3: any 0+ chars other than " ([^"]*) -第3组:除"
  • " - a " char. " -一个"字符。

PHP demo PHP演示

$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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM