如何在文件中获取与给定regexp
匹配的所有文字摘要的行号?
file_content = f.read()
m = re.compile('regexp')
# How to extract line numbers of the matched text snippets?
正则表达式不能跨越行。
答案 0 :(得分:4)
with open(somefile, 'r') as f:
line_numbers = [n for n, line in enumerate(f) if re.search(someRegexp, line)]
答案 1 :(得分:0)
import re
reg="ha*"
count=0
f = open(somefile,'r')
while True:
line= f.readline()
if not line: break
else:
count+=1
if re.search(reg,line):
print count,line