You can use back references in re.sub (online regex here):
import re
data = [
"My email Id is abcd@g mail.com",
"Email Id: defg@yah oo.com",
"id is rock@gmail .com"
]
for s in data:
print(re.sub(r'(@.*)(\s+)(.*)', r'\1\3', s))
Prints:
My email Id is [email protected]
Email Id: [email protected]
id is [email protected]
EDIT:
If the blank space is before the @, the regexp is a little bit tricky (to not match e.g. "aaa bbb ccc [email protected]", online regex here):
import re
data = [
"My email Id is ab [email protected]",
"Email Id: def [email protected]",
"id is roc [email protected]",
"aaa bbb ccc [email protected]"
]
for s in data:
print(re.sub(r'(?=is|:)(.*)\s+(.*@.*)', r'\1\2', s))
Prints:
My email Id is [email protected]
Email Id: [email protected]
id is [email protected]
aaa bbb ccc [email protected]
Now we can combine these regexes:
import re
data = [
"My email Id is ab [email protected]",
"Email Id: def g@ya hoo.com",
"id is roc k@gm ail.com",
"aaa bbb ccc [email protected]"
]
for s in data:
s = re.sub(r'(@.*)\s+(.*)', r'\1\2', s)
s = re.sub(r'(?=is|:)(.*)\s+(.*@.*)', r'\1\2', s)
print(s)
Will print:
My email Id is [email protected]
Email Id: [email protected]
id is [email protected]
aaa bbb ccc [email protected]