Reputation: 10170
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
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
Reputation: 214949
with open(somefile, 'r') as f:
line_numbers = [n for n, line in enumerate(f) if re.search(someRegexp, line)]
Upvotes: 7