在 Python3 中,以下代码用于将 *
的字符串(两个或更多)替换为 x
。
import re
re.sub(r'\*(?=\*)|(?<=\*)\*', 'x', 'Replace this *** but not this *')
# 'Replace this xxx but not this *'
但是,如果我还想豁免作为“单词”一部分的 *
字符串,如下所示怎么办? (即字符串附加到一个或多个 [a-zA-Z]
字符。)
text = "Don't replace foo*** or **bar, either."
# unmodified text expected
我该怎么做?我可能也可以匹配豁免的情况并使用替换函数来处理它们,但是有没有更好的方法?
最佳答案
regex = r"\s\*{2,}[\s\n]"
这匹配 2 个或更多 *
字符,由空格包围(或以换行符结尾)
可以这样调用它吗?
regex = r"\s\*{2,}[\s\n]"
def replacer(match):
return 'x' * len(match.group())
re.sub(regex, replacer, your_string_here)
关于python - 只有在重复而不是单词的一部分时才用另一个替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389122/