使用正则表达式从文件打印有效的电子邮件ID [英] Printing valid email ids from a file using regular expressions

查看:71
本文介绍了使用正则表达式从文件打印有效的电子邮件ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从名为mbox.txt的文件中打印所有以@ gmail.com结尾的有效电子邮件ID

i尝试以下列方式执行此操作,但输出错误。如何我纠正了吗?



我的尝试:



< pre lang =Python>



 import re 

def validitycheck():
fhandle = open(rC:\\Users\\Aishwarya \Desktop\\ temp.txt)
for fhandle:
if line.endswith( @ gmail.com):
print(line)
line = mailid
pattern = re.compile(r[\\\ .-] + @ [\\\ w.-] +.\w+@gmail.com)
matchobject = pattern.match(mailid)

if(matchobject):
print(your mail id,line, 有效)
else:
print(你的邮件ID无效)
else:
print(no mail id a这样的)

validitycheck()

解决方案

为什么你的正则表达式包含两个'@'字符?这是合法的,但只能在带引号的字符串中作为local-string的一部分:电子邮件地址 - 维基百科 [ ^ ]

Isn 't

 [\ w .-] + @ gmail\.com 

更合适?


i want to print all the valid email ids which are ending with @gmail.com from a file named mbox.txt
i tried to do it in the following way but getting the output wrong.How do i correct it?

What I have tried:


import re

def validitycheck():
        fhandle = open(r"C:\\Users\\Aishwarya\Desktop\\temp.txt")
        for line in fhandle:
          if line.endswith("@gmail.com"):
            print (line)
            line = mailid
            pattern = re.compile(r"[\w.-]+@[\w.-]+.\w+@gmail.com")
            matchobject = pattern.match(mailid)
            
            if(matchobject):
                print("your mail id",line,"is valid")
            else:
                print("your mail id is invalid")
          else:
             print("no mail id as such")

validitycheck()

解决方案

Why does your regex contain two '@' characters? It's legal, but only within a quoted string as part of the local-string: Email address - Wikipedia[^]
Isn't

[\w.-]+@gmail\.com

more appropriate?


这篇关于使用正则表达式从文件打印有效的电子邮件ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆