问题:re.error: unbalanced parenthesis at position 88

在使用Python正则表达式的时候,用替换方法出现上述错误,

下面是错误代码:

1
2
3
4
5
new_url = "https://jums.club/images/article/20191227161526664.png)"
old_url = "https://img2018.cnblogs.com/blog/1212206/201912/1212206-20191227161526664-2133632479.png)"
line = "![list example](https://img2018.cnblogs.com/blog/1212206/201912/1212206-20191227161526664-2133632479.png)"
new_line = re.sub(old_url,new_url,line)
print(new_line)

错误提示:

error

错误原因:

reason
我们可以看到,需要替换的两个字符串末尾多出一个)来,导致匹配出错。我们去掉末尾那个)就可以了。

更正代码:

1
2
3
4
5
6
line = '![list example](https://img2018.cnblogs.com/blog/1212206/201912/1212206-20191227161526664-2133632479.png)'
old_url = "https://img2018.cnblogs.com/blog/1212206/201912/1212206-20191227161526664-2133632479.png"
new_url = "https://jums.club/images/article/20191227161526664.png"
l = re.sub(old_url,new_url,line)
print(line)
print(l)

正确运行结果:

right result

写在最后

欢迎大家关注鄙人的公众号【麦田里的守望者zhg】,让我们一起成长,谢谢。
微信公众号