英文:
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
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论