我正在尝试匹配一段文本中的词组。基本上我想要每个单词有 4 个或更多字符,每组 2 个单词,其中第一个单词为 4 个或更多,第二个单词为 3 个或更多字符,每组 3 个单词,第一个单词有 4 个或更多字符,并且第二个和第三个具有 3 个或更多字符。
我的问题是,我尝试为此创建一个正则表达式,只返回匹配一次文本的给定部分,我想获得所有匹配项。
例如,当我有这段文字时: “这是一个示例文本,用于解释我在使用正则表达式时遇到的问题”
它应该返回一个包含以下值的数组:
This
example
text
explain
problem
having
with
regular
expression
example text
explain the
having with
with the
regular expression
explain the problem
having with the
with the regular
我已经尝试了单个和单独的正则表达式,但问题仍然是它一次只能匹配字符串的一部分。例如,如果我尝试以下正则表达式:
/\b(\w{4,}\s\w{3,}\s\w{3,})\b/
应该匹配
having with the
with the regular
我也试过
/\b(?<triple>(?<double>(?<single>\w{4,})(\s\w{3,})?)(\s\w{3,})?)\b/
也只匹配
This
example
explain
having
regular
example text
explain the
having with
regular expression
explain the problem
having with the
有人知道如何解决这个问题吗?
最佳答案
问题是您想要捕捉重叠的模式(例如“有”和“有”)。你可以通过一些巧妙的前瞻来做到这一点。我还没有设法用这种方法组合成一个正则表达式,但你可以这样做:
$text = 'This is an example text to explain the problem I am having with the regular expression';
preg_match_all('/\b(\w{4,})\b/', $text, $matches1);
preg_match_all('/\b(?=(\w{4,}\s+\w{3,}))\b/', $text, $matches2);
preg_match_all('/\b(?=(\w{4,}\s+\w{3,}\s+\w{3,}))\b/', $text, $matches3);
var_dump(array_merge($matches1[1], $matches2[1], $matches3[1]));
关于php - 正则表达式匹配单词组和先前匹配的单词组的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18530681/