Kevin Kurien
Kevin Kurien

Reputation: 842

Replace subtext of a word

I want to replace this string [email protected] to

[email protected]

this is what I have done so far

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

Upvotes: 0

Views: 86

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

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 = "[email protected]"

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

[email protected]

Upvotes: 1

Related Questions