Perl RegEx:返回一个匹配的嵌套 "or" 子组
Perl RegEx: returning one match of nested "or" subgroup
假设我有一条短信
The quick brown fox jumps (over) the lazy dog
。
然后我希望我的 RegEx 模式为 return,例如 hello
(文本中不存在)或括号内的任何单词,在本例中为 over
。
所以这样的模式:
/((hello)|(\([^\)]+\)))/
不过我希望它 return 一个 匹配这个。这只有在优先考虑时才有意义。即:
- 如果
hello
在此字符串中,则 </code> 应为 <code>hello
。
- 如果
hello
不在正文中,那么return如果你能找到括号里的任何内容。
所以在
The quick brown fox jumps (over) the lazy dog
</code> 应该包含字符串 <code>over
。而在
hello! The quick brown fox jumps (over) the lazy dog
</code> 应该包含字符串 <code>hello
.
https://regex101.com/r/H5bwKs/2
有没有办法在一个表达式中做到这一点?
使用 branch reset 结构和贪心点。订单事项:
^(?|.*(hello)|.*(\([^)]+\)))
假设我有一条短信
The quick brown fox jumps (over) the lazy dog
。
然后我希望我的 RegEx 模式为 return,例如 hello
(文本中不存在)或括号内的任何单词,在本例中为 over
。
所以这样的模式:
/((hello)|(\([^\)]+\)))/
不过我希望它 return 一个 匹配这个。这只有在优先考虑时才有意义。即:
- 如果
hello
在此字符串中,则</code> 应为 <code>hello
。 - 如果
hello
不在正文中,那么return如果你能找到括号里的任何内容。
所以在
The quick brown fox jumps (over) the lazy dog
</code> 应该包含字符串 <code>over
。而在
hello! The quick brown fox jumps (over) the lazy dog
</code> 应该包含字符串 <code>hello
.
https://regex101.com/r/H5bwKs/2
有没有办法在一个表达式中做到这一点?
使用 branch reset 结构和贪心点。订单事项:
^(?|.*(hello)|.*(\([^)]+\)))