我想从这样的句子中提取单词:
Image
现在,我希望在句子的末尾有一些可选的东西:
I want to (?P<activity>([a-zäöüß\s]+?)+)
I want to have a beer
-> activity: have a beer
如何更改正则表达式,以便I want to (?P<activity>([a-zäöüß\s]+?)+)(?: with my friends)?
I want to have a beer with my friends
-> have a beer with my friends
不会包含在活动中?
答案 0 :(得分:0)
如果你知道在“和我的朋友”之后别的什么就会出现,你可以尝试一个非贪婪的量词并匹配句末:
I want to (?P<activity>([a-zäöüß\s]+?)+?)(?: with my friends)?$
示例:https://regex101.com/r/MG4Ga5/1
否则,也许你可以使用前瞻:
I want to(?P<activity>((?= with my friends)|(\s[a-zäöüß]+))+)
答案 1 :(得分:0)
您可以使用positive lookahead检查后面的内容是with my friends
还是行$
的结尾,如果您想将其设为可选项。
I want to (?P<activity>[a-zäöüß\s]+?)(?= with my friends|$)
<强>解释强>
I want to
(?P<activity>
[a-zäöüß\s]+
?
)
with my friends
或行尾(?= with my friends|$)