相关疑难解决方法(0)

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

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

"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)

知道我错过了什么吗?

谢谢!勒布

python regex string

9
推荐指数
2
解决办法
1万
查看次数

标签 统计

python ×1

regex ×1

string ×1