如何使用正则表达式 (Regex) 过滤 Pandas 系列中的有效电子邮件?
正则表达式是定义搜索模式的字符序列。在这个程序中,我们将使用这些正则表达式来过滤有效和无效的电子邮件。
我们将使用不同的电子邮件定义一个Pandas系列并检查哪个电子邮件是有效的。我们还将使用一个名为re的Python库,它用于正则表达式。
算法
Step 1: Define a Pandas series of different email ids. Step 2: Define a regex for checking validity of emails. Step 3: Use the re.search() function in the re library for checking the validity of the email.
示例代码
import pandas as pd import re series = pd.Series(['jimmyadams123@gmail.com', 'hellowolrd.com']) regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' for email in series: if re.search(regex, email): print("{}: Valid Email".format(email)) else: print("{} : Invalid Email".format(email))输出结果
jimmyadams123@gmail.com: Valid Email hellowolrd.com : Invalid Email
解释
regex变量具有以下符号:
^:字符串开头的锚点
[]:左方括号和右方括号定义一个字符类来匹配单个字符
\ :转义字符
. :点匹配除换行符以外的任何字符
{}:开始和结束大括号用于范围定义
$ :美元符号是字符串结尾的锚点