1

Is it possible to return the line number of regex findall method results in Python?

import re

s="""The
quick
brown
fox
jumps
over
the
lazy
dog
"""

print re.findall('the', s, flags=re.IGNORECASE | re.MULTILINE)

Expected Result: Will return line 1 and 7.

Is this possible without reading the text line by line?

Thanks in advance.

pren
  • 45
  • 2
  • 8
  • No, the regex engine has no concept of textual positions. – metatoaster Oct 05 '17 at 04:11
  • You can use finditer and can get match position but afaik line no in regex is not possible. `<_sre.SRE_Match object; span=(0, 3), match='The'>` `<_sre.SRE_Match object; span=(31, 34), match='the'>` – Aaditya Ura Oct 05 '17 at 04:23
  • There are so many duplicates of this question. Why do you not search before asking? – Tomalak Oct 05 '17 at 04:47
  • Hi Tomalak, this is not a duplicate of question above. Would like to have a solution without looping line by line. – pren Oct 05 '17 at 09:58
  • 1
    This question is not a duplicate... getting line numbers using finditer or findall without enumerating lines hasn't been addressed in the "duplicated" answer. I was going to post a solution but I can't till this is reopened – BPL Aug 15 '19 at 15:17
  • hi there, i know this question is closed but has anyone found an answer to this issue? i am trying to utilize re.findall to utilize its speed when searching using capture groups, but i realized i need to also grab the line numbers. i could iterate through the resulting list but that is no different from reading the file line by line totally defeating the purpose – user3696118 Feb 23 '20 at 02:01

0 Answers0