Python在搜索中的最后一次匹配后插入文本

时间:2012-03-27 21:57:50

标签: python search

我想在python中找到匹配某个模式的最后一行。我想要做的是找到包含某个项目(line_end)的最后一行,并在其后插入一些信息块作为一些新行。到目前为止,我有:

 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>'并且不确定如何使用正则表达式,即使有很好的搜索词 有人可以提供有关如何找到最后一个搜索项目的建议,而不是超越,以便我可以在那里插入一个文本块吗? 谢谢。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

如果文件不大,您可以按相反的顺序阅读:

for line in reversed(open("filename").readlines()):
    if line.rstrip().endswith('</PropertyGroup>'):
        do_something(line)