2012-03-27 69 views
0

我想在python中找到與某個特定模式匹配的最後一行。我想要做的是找到包含特定項目(line_end)的最後一行,並在它後面插入一些信息塊作爲幾行新行。到目前爲止,我有:Python在搜索中最後一次匹配後插入文本

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>'和不知道如何使用正則表達式即使有很好的搜索詞) 有人可以就如何找到最後搜索項建議幫助,而不是超越,從而使我可以在那裏插入一段文字? 謝謝。

+3

你似乎在解析XML與正則表達式。看到[這個問題]接受的答案(http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Irfy 2012-03-27 22:01:26

回答

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

這是如此有用!謝謝。 – Thalia 2012-03-28 17:18:34

+0

@ user1217150謝謝,但如果您操作XML,請參閱lrfy的建議。 – 2012-03-28 17:58:25

1

如果文件不是很大,你可以以相反的順序閱讀:

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