简体   繁体   English

如何在正则表达式中创建动态捕获组?

[英]How do I create a dynamic capturing group in regex?

I have a string like this: 我有一个像这样的字符串:

$str ="
- group1
- group2
- group3
";

Also I have this regex : 我也有这个正则表达式

/(\-\s\w+)\n(\-\s\w+)\n(\-\s\w+)/

As you know, there is three capturing groups: $1 , $2 and $3 . 如您所知,有三个捕获组: $1$2$3 I made those group manually. 我手动创建了这些组。 I mean if I append this to the string above: 我的意思是如果我将此附加到上面的字符串中:

- group4 
- group5

Then that regex doesn't matches them. 然后,该正则表达式与它们不匹配。


Well, I have a constant pattern: (\\-\\s\\w+) , And I want to create a separated capturing group on the number of matches items in the string. 好吧,我有一个恒定的模式: (\\-\\s\\w+) ,我想根据字符串中匹配项的数量创建一个单独的捕获组。 Hare is a few examples: 野兔是几个例子:

Example1: 范例1:

$str="
- group 1
";

I need a regex to give me all the string by $1 . 我需要一个正则表达式来给我所有的字符串, $1


Example2: 范例2:

$str="
- group 1
- group 2
";

I need a regex to give me first line of string ( - group 1 ) by $1 and second line ( - group 2 ) by $2 我需要一个正则表达式来给我第一行字符串( - group 1$1 ,第二行( - group 2$2


Ok well, as you see in the examples above, string is dynamic but it is according to a constant pattern ... Now I want to know how can I create a dynamic capturing group according to the string? 好的,正如您在上面的示例中看到的那样,字符串是动态的,但它是根据恒定模式进行的……现在,我想知道如何根据字符串创建动态捕获组?

Using the m-modifier (multi-line): that will let the match on each line. 使用m-修饰符(多行):可以使每行匹配。

Try using below regex: 尝试使用以下正则表达式:

 preg_match_all('/(\-\s\w+)/m', $str, $matches);
 print_r($matches);

The impossibility to capture repeating groups is a well known limitation . 捕获重复基团的可能性是众所周知的限制

If you know the max repeating pattern, you can set your regex as (ie max=5): 如果您知道最大重复模式,则可以将正则表达式设置为(即max = 5):

/(\-\s\w+)\n(\-\s\w+)?\n?(\-\s\w+)?\n?(\-\s\w+)?\n?(\-\s\w+)?\n?/

and you will find from one to five matches in the groups from 1 to 5. 然后您会在1到5的组中找到1到5个匹配项。
Substantially, you have to repeat (\\-\\s\\w+)?\\n? 基本上,您必须重复(\\-\\s\\w+)?\\n? for the max possible number of repeating pattern. 以获得最大可能的重复模式数量。

Otherwise, if your max possible number is undefined, I don't know other way than construct a dynamic pattern, as: 否则,如果未定义最大可能数,那么除了构造动态模式外,我不知道其他方法,例如:

$regex = '(\-\s\w+)\n';
$regex = '/'.( str_repeat( $regex, preg_match_all( "/$regex/", $str, $matches ) ) ).'/';

The above pattern will works, but I don't know your exactly replace condition, so it can be unusable for your purpose. 上面的模式可以使用,但是我不知道您要完全替换的条件,因此它可能无法用于您的目的。

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

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