user278064
user278064

Reputation: 10170

How to get line numbers of the snippets matching a regexp?

How is it possible to obtain the line numbers of all the text snippets matching a given regexp, within a file?

file_content = f.read()

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

The regular expression cannot span lines.

Upvotes: 2

Views: 793

Answers (2)

kiranmai
kiranmai

Reputation: 17

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

Upvotes: 0

georg
georg

Reputation: 214949

 with open(somefile, 'r') as f:
     line_numbers = [n for n, line in enumerate(f) if re.search(someRegexp, line)]

Upvotes: 7

Related Questions