python正则表达式替换匹配字符串的一部分 [英] python regular expression replacing part of a matched string

查看:52
本文介绍了python正则表达式替换匹配字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个看起来像这样的字符串

i got an string that might look like this

"myFunc('element','node','elementVersion','ext',12,0,0)"

我目前正在检查有效性,效果很好

i'm currently checking for validity using, which works fine

myFunc\((.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\)

现在我想替换第三个参数中的任何字符串.不幸的是,我不能只在第三个位置的任何子字符串上使用 stringreplace,因为相同的子字符串"可以在该字符串中的任何其他位置.

now i'd like to replace whatever string is at the 3rd parameter. unfortunately i cant just use a stringreplace on whatever sub-string on the 3rd position since the same 'sub-string' could be anywhere else in that string.

有了这个和一个 re.findall,

with this and a re.findall,

myFunc\(.+?\,.+?\,(.+?)\,.+?\,.+?\,.+?\,.+?\)

我能够在第 3 个位置获取子字符串的内容,但是 re.sub 不会替换字符串它只是返回我想替换的字符串:/

i was able to get the contents of the substring on the 3rd position, but re.sub does not replace the string it just returns me the string i want to replace with :/

这是我的代码

myRe = re.compile(r"myFunc\(.+?\,.+?\,(.+?)\,.+?\,.+?\,.+?\,.+?\)")
val =   "myFunc('element','node','elementVersion','ext',12,0,0)"

print myRe.findall(val)
print myRe.sub("noVersion",val)

知道我错过了什么吗?

谢谢!塞布

推荐答案

在 re.sub 中,您需要为整个匹配字符串指定替换.这意味着您需要重复您不想更换的零件.这有效:

In re.sub, you need to specify a substitution for the whole matching string. That means that you need to repeat the parts that you don't want to replace. This works:

myRe = re.compile(r"(myFunc\(.+?\,.+?\,)(.+?)(\,.+?\,.+?\,.+?\,.+?\))")
print myRe.sub(r'\1"noversion"\3', val)

这篇关于python正则表达式替换匹配字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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