Python在搜索中最后一次匹配后插入文本
问题描述:
我想在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>
'和不知道如何使用正则表达式即使有很好的搜索词) 有人可以就如何找到最后搜索项建议帮助,而不是超越,从而使我可以在那里插入一段文字? 谢谢。
答
使用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
答
如果文件不是很大,你可以以相反的顺序阅读:
for line in reversed(open("filename").readlines()):
if line.rstrip().endswith('</PropertyGroup>'):
do_something(line)
你似乎在解析XML与正则表达式。看到[这个问题]接受的答案(http://*.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Irfy 2012-03-27 22:01:26