我已经获得了一个由外部应用程序生成的主.xml文件,并希望通过使用python修改和删除一些行来创建几个新的.xmls。用于这些适配器的搜索字符串和替换字符串存储在数组中,例如:
replaceArray = [
[u'ref_layerid_mapping="x4049" lyvis="off" toc_visible="off"',
u'ref_layerid_mapping="x4049" lyvis="on" toc_visible="on"'],
[u'<TOOL_BUFFER RowID="106874" id_tool_base="3651" use="false"/>',
u'<TOOL_BUFFER RowID="106874" id_tool_base="3651" use="true"/>'],
[u'<TOOL_SELECT_LINE RowID="106871" id_tool_base="3658" use="false"/>',
u'<TOOL_SELECT_LINE RowID="106871" id_tool_base="3658" use="true"/>']]因此,我想遍历我的文件,并将所有出现的'ref_layerid_mapping="x4049" lyvis="off" toc_visible="off"'替换为'ref_layerid_mapping="x4049" lyvis="on" toc_visible="on"'等等。不幸的是,"RowID“、”id_tool_base“和”ref_layerid_mapping“的ID值有时会发生变化。因此,我需要的是搜索主文件中整个字符串的匹配,而不管哪个id值在引号之间,并且只替换replaceArray的两个字符串中不同的子字符串(例如,use=“true”而不是use=“false”)。我不太熟悉正则表达式,但我认为我需要这样的东西来搜索?
re.sub(r'<TOOL_SELECT_LINE RowID="\d+" id_tool_base="\d+" use="false"/>', "", sentence)我很高兴任何提示都指向正确的方向!如果您需要更多的信息,或者我的问题有什么不清楚的地方,请告诉我。
发布于 2015-06-09 07:28:50
一种方法是有一个替换文本的函数。该函数将从re.sub获取match对象,并插入从要替换的字符串中捕获的id。
import re
s = 'ref_layerid_mapping="x4049" lyvis="off" toc_visible="off"'
pat = re.compile(r'ref_layerid_mapping=(.+) lyvis="off" toc_visible="off"')
def replacer(m):
return "ref_layerid_mapping=" + m.group(1) + 'lyvis="on" toc_visible="on"';
re.sub(pat, replacer, s)输出:
'ref_layerid_mapping="x4049"lyvis="on" toc_visible="on"'另一种方法是在替换模式中使用反向引用。(见http://www.regular-expressions.info/replacebackref.html)
例如:
import re
s = "Ab ab"
re.sub(r"(\w)b (\w)b", r"\1d \2d", s)输出:
'Ad ad'https://stackoverflow.com/questions/30724715
复制相似问题