Python正则表达式查找包含部分tex的单词

2024-07-02 13:02:41 发布

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

我想在课文中找到这样的短语。(我不知道怎么做)

  1. -是-和-到-在大文本中的短语,或者是-和-到

love-is-beatiful-to-you

love-IS-beatiful-TO-you

loveISbeatifulTOyou

例如

" The sun is black but love-IS-beatiful-TO-you when you smile"

输出

love-IS-beatiful-TO-you

  1. 如果你在句子里发短信,我想整句话

示例

Open your eyes and love. come.fastFORyou immediately

我想得到(如你所见,可以是点和空格)

love. come.fastFORyou


Tags: theto文本youissunblack课文
1条回答
网友
1楼 · 发布于 2024-07-02 13:02:41

考虑使用带有特定regex模式的re.findall()函数的以下解决方案:

import re 

s = " The sun is black but love-IS-beatiful-TO-you when you smile. Open your eyes and love. come.fastFORyou immediately"
result = re.findall(r'(\b\w+-?is-?\w+-?to-?\w+\b|(?:\w+(?:\.|\. )?)+foryou\b)', s, re.I)

print(result)

输出:

['love-IS-beatiful-TO-you', 'love. come.fastFORyou']

相关问题 更多 >