我需要搜索每行中的多个单词,并且如果所有单词在一行中匹配,则打印该行。是否可以在re.search中使用'和'?
file.txt的
This is starting string.
This is starting but different string.
This is starting but the same string.
This is a differnet string.
This is a old string.
i的以下方式所做的那样。
import re
with open("file.txt", "r") as in_file:
for line in in_file:
if (re.search('different',line)) and (re.search('string',line)):
print line
但我需要这样的东西:
if (re.search('different' and 'string',line))::
print line
我知道我们还是为我们所用
if (re.search('different'|'string',line))::
print line
任何人可以帮助我以类似的方式使用“和”。
你为什么要使用正则表达式呢? “所有(在w('不同的','字符串'))中的w也行得通。否则:不,没有'和'正则表达式选项。 –
并且从重复:'re.search(r'(?=。* different)(?=。* string)',line)'也适用于案例。 –
@ martijn-pieters:谢谢你只是记住了基础知识。 – PAR