如何获取与正则表达式匹配的片段的行号?

时间:2012-05-11 21:27:43

标签: python regex

如何在文件中获取与给定regexp匹配的所有文字摘要的行号

file_content = f.read()

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

正则表达式不能跨越行。

2 个答案:

答案 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