python - 在python中使用RegEx用下面的模式替换某个字符

标签 python regex python-3.x

我有如下字符串:

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/

相关文章:

python - 类实例可以知道它是否是一个参数吗?

python - 如何从 csv 文件获取存储聚合值的字典字典

python-3.x - Pandas df.to_sql 不适用于红移

mysql - 如何将数据插入包含一列的表中?

python - 如何获得 pickle 中的物体数量?

python - mrjob bad --steps 在 Hadoop 集群上使用 make_runner 时出错

Python:具有短生命周期键的线程安全字典,这是正确的吗?

c# - 用于准确检测 "071-XXXXXXX"的正则表达式,其中 X 是数字

regex - 理解 sed 命令中的正则表达式

python - 在 Python 中匹配替代正则表达式