【发布时间】:2017-09-24 21:45:31
【问题描述】:
我需要在每一行中搜索多个单词,如果一行中的所有单词都匹配,则打印该行。
文件.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.
我已经按照以下方式完成了。
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
谁能帮助我以类似的方式使用“和”。
【问题讨论】:
-
你为什么要使用正则表达式?
all(w in line for w in ('different', 'string'))也可以。否则:不,没有“和”正则表达式选项。 -
从副本中:
re.search(r'(?=.*different)(?=.*string)', line)也适用于大小写。 -
@martijn-pieters:谢谢你只记得基础知识。
标签: python regex python-2.7