[英]The specific word must be somewhere between two substrings regex python
我有一个regex
来查找以Today开头并以. 或•但介于第一个单词(Today)和最后一个单词(.\•)之间的某个单词the must be in sentence。
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.
但是我写的代码没有检查单词the .
一种经典的方法是使用re.match
function 并根据您的需要调整正则表达式。 您可以使用一些正则表达式文档,例如此处的文档,并根据您的需要进行调整。 使用group()
方法访问结果,当没有匹配时返回 None。
因此,您的代码可能类似于:
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[^.•]*[.•]
\bToday\b
在单词边界之间匹配单词Today
以防止部分匹配[^.•]*
匹配除 . 之外的任何字符 0 次或多次.
或•
\bthe\b
匹配单词the
之间的单词[^.•]*
匹配除 . 之外的任何字符 0 次或多次.
或•
[.•]
匹配其中一个.
或•
例如使用re.findall获取字符串列表:
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)
Output
Today is a beautiful day in one of the last days of April.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.