Python insert text after last match in search
Question: 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.


Answer: Using [re](http://docs.python.org/library/re.html)

    
    
    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):]
    

