如何使用正则表达式 (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))

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

jimmyadams123@gmail.com: Valid Email
hellowolrd.com : Invalid Email

解释

regex 变量包含以下符号

  • ^: 字符串开头的锚点
  • [ ]: 开方括号和闭方括号定义一个字符类,以匹配单个字符
  • : 转义字符
  • : 点号匹配除换行符之外的任何字符
  • {} : 开花括号和闭花括号用于范围定义
  • :  美元符号是字符串结尾的锚点

更新于: 2021年3月16日

716 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告