我有一个文本文件,其中的行要提取与某种模式匹配的一行。我可以使用正则表达式搜索该行并返回它,以便以后使用它吗?有没有比这更优雅的方式
for lines in file:
if re.match(targetregex,line)!=None:
print line
就像是:
print re.matchingline(targetregex,file.read())
您可以像这样使用列表理解
print [line for line in file if re.match(targetregex, line)]
它将返回与正则表达式匹配的行列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句