【发布时间】:2021-10-14 11:14:11
【问题描述】:
假设有一个字符串
"An example striiiiiing with other words"
我需要将'i's 替换为'*'s,例如'str******ng'。 '*' 的数量必须与'i' 相同。仅当连续的'i' 大于或等于 3 时才会发生这种替换。如果'i' 的数量小于 3,则有不同的规则。我可以硬编码:
import re
text = "An example striiiiing with other words"
out_put = re.sub(re.compile(r'i{3}', re.I), r'*'*3, text)
print(out_put)
# An example str***iing with other words
但是 i 的数量可以是任何大于 3 的数字。我们如何使用正则表达式来做到这一点?
【问题讨论】:
-
简单地说,
re.sub("iiiiii", "******", string)。你能更好地解释你的问题吗?只有“我”吗?有没有重复的字母?有没有重复的字符?是从第四个字符开始的任意六个字符吗?...
标签: python-3.x regex