我可以使用 re.sub(或 regexobject.sub)来替换子组中的文本吗? [英] Can I use re.sub (or regexobject.sub) to replace text in a subgroup?

查看:40
本文介绍了我可以使用 re.sub(或 regexobject.sub)来替换子组中的文本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析一个看起来像这样(简化)的配置文件:

I need to parse a configuration file which looks like this (simplified):

<config>
<links>
<link name="Link1" id="1">
 <encapsulation>
  <mode>ipsec</mode>
 </encapsulation>
</link>
<link name="Link2" id="2">
 <encapsulation>
  <mode>udp</mode>
 </encapsulation>
</link>
</links>

我的目标是能够更改特定链接的特定参数,但我无法让替换正常工作.我有一个可以隔离特定链接上的参数值的正则表达式,该值包含在捕获组 1 中:

My goal is to be able to change parameters specific to a particular link, but I'm having trouble getting substitution to work correctly. I have a regex that can isolate a parameter value on a specific link, where the value is contained in capture group 1:

link_id = r'id="1"'
parameter = 'mode'
link_regex = '<link [\w\W]+ %s>[\w\W]*[\w\W]*<%s>([\w\W]*)</%s>[\w\W]*</link>' \
% (link_id, parameter, parameter)

因此,

print re.search(final_regex, f_read).group(1)

印刷品网络安全

regex howto 中的示例似乎都假设人们想要使用替换中的捕获组,但我需要做的是替换捕获组本身(例如,将 Link1 模式从 ipsec 更改为 udp).

The examples in the regex howto all seem to assume that one wants to use the capture group in the replacement, but what I need to do is replace the capture group itself (e.g. change the Link1 mode from ipsec to udp).

推荐答案

我不确定我会这样做,但最快的方法是转移捕获:

not sure i'd do it that way, but the quickest way would be to shift the captures:

([\w\W][\w\W]<%s>)[\w\W]([\w\W])' 并替换为 group1 +mode+group2

([\w\W][\w\W]<%s>)[\w\W]([\w\W])' and replace with group1 +mode+group2

这篇关于我可以使用 re.sub(或 regexobject.sub)来替换子组中的文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆