bon*_*ang 6 python regex python-3.x
在Python3,下面的代码工作以替换的字符串(两个或更多)*的用x的。
import re
re.sub(r'\*(?=\*)|(?<=\*)\*', 'x', 'Replace this *** but not this *')
# 'Replace this xxx but not this *'
Run Code Online (Sandbox Code Playgroud)
但是,如果我还想免除*作为“单词”一部分的的字符串,如下所示,该怎么办?(即字符串附加到一个或多个[a-zA-Z]字符。)
text = "Don't replace foo*** or **bar, either."
# unmodified text expected
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?我可能也可以匹配豁免案例,并使用替换函数来处理它们,但是有更好的方法吗?
regex = r"\s\*{2,}[\s\n]"
Run Code Online (Sandbox Code Playgroud)
此匹配2个或更多*字符,用空格包围(或以换行符结尾)
可以这样称呼它吗?
regex = r"\s\*{2,}[\s\n]"
def replacer(match):
return 'x' * len(match.group())
re.sub(regex, replacer, your_string_here)
Run Code Online (Sandbox Code Playgroud)