下面是使用正则表达式和多行模式来比较行是否包含短语的代码示例:
import re
def check_phrase_in_lines(phrase, lines):
pattern = re.compile(phrase, re.MULTILINE)
matching_lines = []
for line in lines:
if re.search(pattern, line):
matching_lines.append(line)
return matching_lines
# 示例用法
lines = [
"This is line 1.",
"This line contains the phrase.",
"Another line here.",
"Line with another phrase."
]
phrase = "phrase"
matching_lines = check_phrase_in_lines(phrase, lines)
print(matching_lines)
上述代码中,check_phrase_in_lines
函数接受一个短语和一个行列表作为输入参数。它使用re.compile
函数创建一个正则表达式模式,并设置多行模式。然后,它遍历行列表,并使用re.search
函数查找匹配短语的行,如果找到了匹配的行,则将其添加到matching_lines
列表中。最后,函数返回包含匹配短语的行的列表。
在示例中,我们使用了一个包含4行的行列表和一个短语"phrase"。运行代码后,将返回包含短语的行的列表,即["This line contains the phrase.", "Line with another phrase."]
。
上一篇:比较行计数的结果
下一篇:比较行以查看客户是否更换了产品