python - 只有在重复而不是单词的一部分时才用另一个替换字符

标签 python regex python-3.x

在 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/

相关文章:

python - Pandas :如果多个列中的一个以上为零,则删除行

python - 下降栏是周末。选择仅工作日索引的列

python - 大型正则表达式模式中的正则表达式 'sre_constants.error: bad character range'

regex - PCRE 负前瞻给出意外匹配

python - 2 人骰子游戏,其中偶数总得分和奇数总失分 NEA 任务计算机科学

python - 在 x 秒后运行某些代码,在 python 中每 n 秒运行一次

python - Tweepy 速率错误

regex - 加载错误 : PCRE compilation error: lookbehind assertion is not fixed length

python - 为什么在我的类里面使用 __slots__ 不会改变大小?

python - 如何解析列表的列表并将元素一起分析以查看它们随时间出现了多少次?