特定单词必须位于两个子字符串regex python之间
我有一个特定单词必须位于两个子字符串regex python之间,python,regex,Python,Regex,我有一个正则表达式来查找以今天开头,以或•结尾的句子,但是在第一个单词(今天)和最后一个单词(.\•)之间的某个地方,这个词必须在句子中 description = 'Today is a beautiful day in one of the last days of April. Other sentence ...' pattern = re.finditer("(Today).*?[\.•]", description, re.IGNORECASE) for i in
正则表达式
来查找以今天开头,以或•结尾的句子,但是在第一个单词(今天)和最后一个单词(.\•)之间的某个地方,这个词必须在句子中
description = 'Today is a beautiful day in one of the last days of April. Other sentence ...'
pattern = re.finditer("(Today).*?[\.•]", description, re.IGNORECASE)
for i in pattern:
print(i.group(0))
# desired output: Today is a beautiful day in one of the last days of April.
但是我写的代码没有检查单词,一个经典的方法是使用
re.match
函数并根据需要调整正则表达式。您可以使用一些regex文档,如一个,并根据您的需要进行调整。
使用group()
方法访问结果,如果没有匹配项,则不会返回任何结果
因此,您的代码可能类似于:
import re
description = 'Today is a beautiful day in one of the last days of April. fds'
pattern = re.finditer("(^Today).*( the +).*(\.|•)", description, re.IGNORECASE)
for i in pattern:
print(i.group(0))
上面写着“今天是四月最后几天中的一个美丽的日子。”
当省略单词“the”时,不会打印任何内容。如果
和•
都不允许,则可以使用2[^.•]
匹配除所列字符以外的任何字符,而无需使用捕获组
\bToday\b[^.•]*\bthe\b[^.•]*[.•]
在单词边界之间匹配单词\b今天\b
以防止部分匹配
匹配任何字符0次或更多次,除了[^.•]*
或•
匹配单词之间的\b\b
和
匹配任何字符0次或更多次,除了[^.•]*
或•
匹配[.•]
或•
import re
description = 'Today is a beautiful day in one of the last days of April. Other sentence ...'
pattern = re.findall(r"\bToday\b[^.•]*\bthe\b[^.•]*[.•]", description, re.IGNORECASE)
for s in pattern:
print(s)
输出
Today is a beautiful day in one of the last days of April.
正如我写的“寻找句子”一样,我想要的是今天以
开头,以结尾的句子,我不想要字符串的其余部分。我更新了问题。你的回答也可以接受类似于的东西。你的问题不清楚。你想要的正是“那个”这个词?在正则表达式前后添加一个空格,就像我刚刚编辑了我的答案一样。结尾符号不一定在结尾?删除$
符号。流中的最后一个单词与您要查找的正则表达式中的最后一个序列之间存在差异。无论如何,您要查找的最后一个元素(dot
或circle
)符号不在流的末尾,它必须在“the”之后。确切地说是“the”?是的,没错。你的答案仍然不是我想要的。例如,今天的输出是四月最后一天中的一个美丽的日子。fds.
必须今天是四月最后几天中的一个美丽的日子。