如果我在比赛中寻找锚词,例如句子中的单词颜色如果该句子中有颜色但在OR之后匹配正常:
我能用一两个正则表达式做这个吗我需要两个:
(Color (Red|Blue|Orange))
https://regex101.com/r/iT4nN6/1
((Red|Blue|Orange) Color)
答案 0 :(得分:1)
你可以做一个正则表达式:
((Red|Orange|Blue) Color|Color (Red|Orange|Blue)
如果事情变得更复杂,那么维护起来会更困难;你需要在两个地方更新颜色列表。根据您的具体情况,单独执行这两个组件可能更容易,只在另一个组件的结果中查找一个组件。
答案 1 :(得分:0)
在PHP PCRE正则表达式语法中,您可以利用(?J)
修饰符,该修饰符允许对不同的捕获组使用相同的名称:
(?J)(?<colorword>Color)\h+(?<color>Reddish|Red|Blue|Orange)|(?<color>Reddish|Red|Blue|Orange)\h+(?<colorword>Color)
$clrw = '(?<colorword>Color)';
$clr = '(?<color>Reddish|Red|Blue|Orange)';
$re = '~(?J)' . $clrw . '\h+' . $clrw . '|' . $clr . '\h+' . $clrw . '~i';
$str = " I WANT TO EXTRACT CAPTURING GROUP 2 AS COLOR AND I DO:\nand love the Color Red\n \nI WANT TO EXTRACT CAPTURING GROUP 2 AS COLOR BUT I DONT AS I HAVE TO REVERSE THE GROUPS TI ((Red|Blue|Orange) Color):\nit had a reddish color\n\nI DON'T WANT ANYTHING BECAUSE IT ISN'T PRECEDED OR FOLLOWED BY THE WORD COLOR\nit is a red dawn \nI took the red eye home\nit was the color red";
preg_match_all($re, $str, $matches, PREG_SET_ORDER);
for ($i = 0; $i < count($matches); $i++) {
echo $matches[$i]["color"] . ": " . $matches[$i]["colorword"] . PHP_EOL;
}
结果:
Red: Color
reddish: color
red: color