python - 在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
.
欢迎任何建议
谢谢,
解决方案
在将电子邮件地址与空格匹配后,您可以使用可调用来删除空格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
推荐阅读
- android - 当应用程序被杀死时,AlarmManager 不会一直工作
- arrays - 无法将数据从文件复制到结构数组 (c)
- python - Dataproc 退出代码 247
- cytoscape.js - cytoscape.js 中是否有边缘加权弹簧嵌入式布局?
- c - 在C语言中以日期为dd/mm/yy并以“合法”形式显示日期
- python - 将 RAPIDS CUML 随机森林模型部署到无法安装 RAPIDS/CUML 的 Windows 虚拟机
- python - 可以在 Python API 中参数化查询名称变量吗?
- python - 如何调试在 Docker 容器中运行的 Flask 应用程序?
- reactjs - 与主页相同的新页面反应
- cuda - 半浮点数的 FLT_MAX