如何为以下场景编写正则表达式?

2024-04-20 16:34:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为下面的场景编写一个正则表达式

正则表达式:?你知道吗

例1

输入:

I got good morning message

输出:

good morning

例2

输入

good morning message

输出

good morning

例3

输入:

my friend got thank you message from xyz

输出:

thank you

输出应该通过忽略其他细节来包含消息,比如i gotmessagemy friend got。消息不仅可以是good morningthank you。你知道吗


Tags: fromfriendyou消息messagemy场景细节
2条回答

如果要获取got和message关键字之间的字符串,或者如果字符串中没有got,则从字符串的开头进行匹配,则可以使用以下代码:

import re

pattern = re.compile('(?:.*got )?(?(1)got |)(.*) message')
pattern.search('my friend got thank you message from xyz').group(1)

如果我理解正确,您希望从got和message之间获取消息,或者如果找不到got,则从字符串的开头获取消息?你知道吗

在这种情况下,您可以使用:

[^|got ](.*) message

然后,您可以通过执行\1来提取捕获组(程序或语言可能有点不同)。你知道吗

相关问题 更多 >