我正在编写一个python工具来处理一组文件。这个工具将被其他用户使用,而不是我。在
文件类似于以下格式:
#Text which I want to keep intact
#Lots of text
#Lots and lots of text
#Lots and lots and lots of other text
#Then in-between the file I have text in this format which I want to operate on:
ginstance
{
name ginstance_053D627B1349FA0BC57
node "FINDME"
inherit_xform on
visibility 255
blah
blah
blah
}
ginstance
{
name ginstance_053D627B1349FA0BC57
node "DONTFINDME"
inherit_xform on
visibility 255
blah
blah
blah
}
我想做的是:
我的工具将从使用UI的用户那里获取此搜索项(“FINDME”)。在
我可以找到要删除的实例:
^{pr2}$此外,此代码从输入文件中删除所有实例并将结果写入输出:
^{3}$但我不想删除所有实例,只删除其中包含“FINDME”的实例。 如何编写一个包含这两个因素的python代码呢。在
希望我能清楚地回答这个问题。非常感谢。在
我搜索了很多关于堆栈溢出的问题,并且在发布这个问题之前尝试了很多答案。在
试试这个
Regex Demo
输入
^{pr2}$输出
你不认为
FINDME
也存在于DONTFINDME
中吗?这就是为什么它是匹配的两个。如果它在quotes
,那么使用这个或者更好的方法是使用
^{pr2}$re.search()
。它包含单词边界(\b
)你可以采用这种方法:
它假定,
^{pr2}$ginstance
的内部块中没有其他}
。在
Python
中,这将是:请参见a demo on regex101.com以及on ideone.com。在
相反:
考虑到你的意见(为了达到相反的效果),你可以采用消极的前瞻性解决方案,如下所示:
也可以参见这个one on regex101.com的演示。在
相关问题 更多 >
编程相关推荐