问题描述
我有一些想要匹配的短语.我使用了如下正则表达式:
I have some short phrases that I want to match on. I used a regex as follows:
(^|)(piston|piston ring)( |$)
使用上述内容,regex.match("piston ring")
匹配piston".如果我更改正则表达式,使较长的短语活塞环"先出现,那么它会按预期工作.
Using the above, regex.match("piston ring")
matches on "piston". If I change the regex such that the longer phrase "piston ring" comes first then it work as expected.
我对这种行为感到惊讶,因为我假设正则表达式的贪婪性质会尝试免费"匹配最长的字符串.
I was surprised by this behavior as I was assuming that the greedy nature of regex would try to match the longest string "for free."
我错过了什么?有人可以解释一下吗?谢谢!
What am I missing? Can somebody explain this? Thanks!
推荐答案
在正则表达式中使用交替 (|
) 时,会按从左到右的顺序尝试每个选项,直到找到匹配项.因此,在您的示例中,由于可以使用 piston
进行匹配,因此永远不会尝试 piston ring
.
When using alternation (|
) in regular expressions, each option is attempted in order from left to right until a match can be found. So in your example since a match can be made with piston
, piston ring
will never be attempted.
编写此正则表达式的更好方法是这样的:
A better way to write this regex would be something like this:
(^|)(piston( ring)?)( |$)
这将尝试匹配 'piston'
,然后立即尝试匹配 ' ring'
,其中 ?
使其成为可选.或者,只需确保在交替开始时出现更长的选项.
This will attempt to match 'piston'
, and then immediately attempt to match ' ring'
, with the ?
making it optional. Alternatively just make sure your longer options occur at the beginning of the alternation.
您可能还想考虑使用 词边界、\b
,而不是 (^|)
和 (|$)
.
You may also want to consider using a word boundary, \b
, instead of (^|)
and ( |$)
.
这篇关于使用正则表达式和 Python 进行短语匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!