替换词的子文本

huangapple go评论81阅读模式
英文:

Replace subtext of a word

问题

我想要替换这个字符串
ramesh@gmail.com

rxxxxh@gxxxl.com

我目前已经完成的部分是

print( re.sub(r'([A-Za-z](.*)[A-Za-z]@)','x', i))

英文:

I want to replace this string
ramesh@gmail.com

to

rxxxxh@gxxxl.com

this is what I have done so far

print( re.sub(r'([A-Za-z](.*)[A-Za-z]@)','x', i))

答案1

得分: 1

Sure, here is the translated code:

使用捕获组的一种方法在应该用 `x` 替换的部分中返回匹配组中字符数的重复

对于第二个和第四个组请使用否定字符类 `[^` 匹配除列出的字符之外的任何字符

\b([A-Za-z])([^@\s]*)([A-Za-z]@[A-Za-z])([^@\s.]*)([A-Za-z])\b

I've translated the code part as requested.

英文:

One way to go is to use capturing groups and in the replacement for the parts that should be replaced with x return a repetition for number of characters in the matched group.

For the second and the fourth group use a negated character class [^ matching any char except the listed.

\b([A-Za-z])([^@\s]*)([A-Za-z]@[A-Za-z])([^@\s.]*)([A-Za-z])\b

Regex demo | Python demo

For example

import re

i = "ramesh@gmail.com"

res = re.sub(
    r'\b([A-Za-z])([^@\s]*)([A-Za-z]@[A-Za-z])([^@\s.]*)([A-Za-z])\b',
    lambda x:  x.group(1) + "x" * len(x.group(2)) + x.group(3) + "x" * len(x.group(4)) + x.group(5),
i)
print(res)

Output

rxxxxh@gxxxl.com

huangapple
  • 本文由 发表于 2020年1月3日 17:41:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定