使用Regex查找和替换电子邮件地址

2024-03-29 13:06:01 发布

您现在位置:Python中文网/ 问答频道 /正文

Python新手,希望将其与Regex一起使用,以处理5k+个电子邮件地址的列表。我需要改变封装每个地址与任何引号。我使用\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b来标识每个电子邮件地址。如何替换的当前条目user@email.com到“user@email.com“在每个5k电子邮件地址周围添加引号?你知道吗


Tags: com列表电子邮件email地址条目标识引号
1条回答
网友
1楼 · 发布于 2024-03-29 13:06:01

您可以使用re.sub模块并像这样使用反向引用:

>>> a = "this is email: someone@mail.com and this one is another email foo@bar.com"
>>> re.sub('([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})', r'"\1"', a)

'this is email: "someone@mail.com" and this one is another email "foo@bar.com"'

更新:如果您有一个文件要替换其中每行的电子邮件,您可以这样使用readlines()

import re

with open("email.txt", "r") as file:
    lines = file.readlines()

new_lines = []
for line in lines:
    new_lines.append(re.sub('([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})', r'"\1"', line))

with open("email-new.txt", "w") as file:
    file.writelines(new_lines)

你知道吗电子邮件.txt地址:

this is test@something.com and another email here foo@bar.com
another email abc@bcd.com
still remaining someone@something.com

电子邮件-新建.txt(运行代码后):

this is "test@something.com" and another email here "foo@bar.com"
another email "abc@bcd.com"
still remaining "someone@something.com"

相关问题 更多 >