首页 > 解决方案 > 在python中使用RegEx将某个字符替换为以下模式

问题描述

我有如下字符串:

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.

欢迎任何建议

谢谢,

标签: pythonregexpython-3.x

解决方案


在将电子邮件地址与空格匹配后,您可以使用可调用来删除空格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

推荐阅读