python正则表达式替换匹配字符串的一部分

Seb*_*Seb 9 python regex string

我有一个字符串可能看起来像这样

"myFunc('element','node','elementVersion','ext',12,0,0)"
Run Code Online (Sandbox Code Playgroud)

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

myFunc\((.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\)
Run Code Online (Sandbox Code Playgroud)

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

用这个和re.findall,

myFunc\(.+?\,.+?\,(.+?)\,.+?\,.+?\,.+?\,.+?\)
Run Code Online (Sandbox Code Playgroud)

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

这是我的代码

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

print myRe.findall(val)
print myRe.sub("noVersion",val)
Run Code Online (Sandbox Code Playgroud)

知道我错过了什么吗?

谢谢!勒布

Mar*_*wis 7

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

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


Ian*_*ley 1

您是否尝试过使用命名组?http://docs.python.org/howto/regex.html#search-and-replace

希望这能让你只瞄准第三场比赛。