2

如何在文件中获取与给定匹配的所有文本片段的行号regexp

file_content = f.read()

m = re.compile('regexp')
# How to extract line numbers of the matched text snippets?

正则表达式不能跨行。

4

2 回答 2

6
 with open(somefile, 'r') as f:
     line_numbers = [n for n, line in enumerate(f) if re.search(someRegexp, line)]
于 2012-05-11T21:40:40.420 回答
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
于 2012-05-12T04:46:21.420 回答