使用正则表达式与非贪婪秒


Using regex with non-greedy second

我有一个匹配字符串并使用非贪婪语法的正则表达式,因此它在第一个结束匹配时停止。我需要它在第二场比赛结束时停止。我该怎么做呢?

$text = "start text1 end text2 end text3 end";
$regex = "~start.+?end~";
preg_match($regex, $text, $match);
print_r($match);

结果:

start text1 end

需求结果

start text1 end text2 end

下面应该可以工作,您只需要再次重复您想要的表达式序列。有几种方法可以做到这一点。最简单的方法是:

$text = "start text1 end text2 end text3 end";
$regex = "~start.+?end.+?end~";
preg_match($regex, $text, $match);
print_r($match);

您可能还需要使用精确量词来描述模式:

$text = "start text1 end text2 end text3 end";
$regex = "~start(.+?end){2}~";
preg_match($regex, $text, $match);
print_r($match);

"{2}"告诉它匹配它前面括号中的所有内容两次。