我有如下字符串:
s1 = "My email Id is abcd@g mail.com"
s2 = "john@ hey.com is my email id"
s3 = "id is rock@gmail .com"
s4 = "The id is sam @yahoo.in"
我必须使用正则表达式替换电子邮件 ID 中的空格。 我怎样才能实现这个目标?
我试过了
s = re.sub(r'@\w*[\s]+[\w]*\.', r'', s1)
它给我的输出为:
'My email Id is abccom'
输出应该是:
'My email Id is abc@gmail.com'
我不确定如何用 re.sub
替换空白值。
欢迎任何建议
谢谢
最佳答案
在使用 re.sub
将电子邮件地址与空格匹配后,您可以使用可调用函数来删除空格。
import re
l = [
"My email Id is abcd@g mail.com",
"john@ hey.com is my email id",
"id is rock@gmail .com",
"The id is sam @yahoo.in"
]
for s in l:
print(re.sub(r'[\w.-]+ ?@(?:[\w-]+\.[\w -]+|[\w -]+\.[\w-]+)', lambda e: e[0].replace(' ', ''), s))
输出:
My email Id is abcd@gmail.com
john@hey.com is my email id
id is rock@gmail.com
The id is sam@yahoo.in
关于python - 在python中使用RegEx用下面的模式替换某个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51649789/