如何在文件中获取与给定匹配的所有文本片段的行号regexp
?
file_content = f.read()
m = re.compile('regexp')
# How to extract line numbers of the matched text snippets?
正则表达式不能跨行。
with open(somefile, 'r') as f:
line_numbers = [n for n, line in enumerate(f) if re.search(someRegexp, line)]
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