【问题标题】:How to substitute a repeating character with the same number of a different character in regex python?如何在正则表达式python中用相同数量的不同字符替换重复字符?
【发布时间】: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


【解决方案1】:

i{3} 模式只匹配字符串中的任何位置的iii。您需要i{3,} 来匹配三个或更多is。但是,要使这一切正常工作,您需要将匹配传递给用作 re.sub 的替换参数的可调用对象,您可以在其中获取匹配文本长度并正确乘法。

此外,建议在 re.sub 之外声明正则表达式,或者只使用字符串模式,因为模式已缓存。

这是解决问题的the code

import re
text = "An example striiiiing with other words"
rx = re.compile(r'i{3,}', re.I)
out_put = rx.sub(lambda x: r'*'*len(x.group()), text)
print(out_put)
# => An example str*****ng with other words

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2020-03-28
    相关资源
    最近更新 更多