Python 正则表达式匹配包含 'des' 的句子
以下代码使用 Python 正则表达式匹配包含 'des' 的句子,并输出匹配的句子:
import re
sentences = ['This is a test sentence with des in it.',
'I am not sure what to do next.',
'The destination is still uncertain.']
pattern = r'.*des.*'
for sentence in sentences:
if re.match(pattern, sentence):
print(sentence)
输出:
This is a test sentence with des in it.
The destination is still uncertain.
解释:
- 使用正则表达式模式
'.*des.*'来匹配包含 'des' 的句子。该模式表示任意字符(包括空格)出现任意次数,然后是一个单词边界\b,然后是 'des',再是另外的任意字符。 - 遍历句子列表,对于每个句子,使用
re.match()函数来检查是否符合模式。 - 如果符合,则打印该句子。
原文地址: https://www.cveoy.top/t/topic/n8vQ 著作权归作者所有。请勿转载和采集!