1

I would like to find the last line matching a certain pattern, in python. What I am trying to do is find the last line that contains a certain item (line_end), and insert a block of information as a few new lines after it. So far I have:

 text = open( path ).read()
 match_found=False
 for line in text.splitlines():
     if line_pattern in line:
         match_found=True
 if not match_found:

(line_end='</PropertyGroup>' and not sure how to use regex even with nice search words) Can somebody help with advice on how to find the last search item, and not go beyond, so that I can insert a block of text right there ? Thank you.

Thalia
  • 13,637
  • 22
  • 96
  • 190
  • 3
    You seem to be parsing XML with regular expressions. See the accepted answer to [this question](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Irfy Mar 27 '12 at 22:01

2 Answers2

4

Using re

import re

text = open( path ).read()
match_found=False
matches = re.finditer(line_pattern, text)

m = None      # optional statement. just for clarification
for m in matches:
   match_found=True
   pass       # just loop to the end

if (match_found):
   m.start()  # equals the starting index of the last match
   m.end()    # equals the ending index of the last match 

   # now you can do your substring of text to add whatever
   #   you wanted to add. For example,
   text[1:m.end()] + "hi there!" + text[(m.end()+1):]
Apprentice Queue
  • 2,036
  • 13
  • 13
1

If the file is not big, you could read it in reverse order:

for line in reversed(open("filename").readlines()):
    if line.rstrip().endswith('</PropertyGroup>'):
        do_something(line)
alextercete
  • 4,871
  • 3
  • 22
  • 36