在只包含特定字符的字符串中查找单词

2024-05-15 17:05:15 发布

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

我正在尝试编写regex来查找只包含特定字符的单词。你知道吗

例如:

text= "I want to mes a message saying mess"

我希望regex找到只包含“m”“e”“s”字符的单词,即mes和mess。你知道吗

我不希望regex找到消息,因为它包含除“m”“e”“s”以外的其他字符。你知道吗

reg= r"(?:[mes"]){1,}是我正在尝试的。。。。你知道吗

你能帮我写一个正则表达式吗?它包含以我开头的单词,但不包含像“男人餐”这样的单词

text=" Regex should find mess mean and all words starting with me except men and meal"

输出应仅为:mess mean me

谢谢。。。你知道吗


Tags: andtotext消息messageregmean字符
3条回答

我认为这是\b[mes]+\b,但我认为有更多的方法可以做到这一点

这是我的方式,没有正则表达式

text = "I want to mes a message saying mess".split()
rtext = [t for t in text if t.find("me") == 0] # only find word begin with `me`
xtext = [t for t in text if "me" in t] #May be too broad
print(rtext)

Also can you please help me in writing a regex which contains words starting with me but does not contain words like men meal

是的。请尝试以下操作:

(?!(\bmeal\b)|(\bmen\b))\bme\w+

see this link for explanation and demo

相关问题 更多 >