pandas笔记(三)-- 查找有效邮箱的用户(正则表达式应用)
题目描述
一个有效的电子邮件具有前缀名称和域,其中:
- 前缀 名称是一个字符串,可以包含字母(大写或小写), 数字,
'_','.', 和破折号'—', 前缀名必须以字母开头- 域名 为
'@leetcode.com'
编写一个解决方案,以查找具有有效电子邮件的用户, 以任何顺序返回结果表。
测试用例
输入
| user_id | name | |
|---|---|---|
| 1 | Winston | winston@leetcode.com |
| 2 | Jonathan | jonathanisgreat |
| 3 | Annabelle | bella-@leetcode.com |
| 4 | Sally | sally.come@leetcode.com |
| 5 | Marwan | quarz#2020@leetcode.com |
| 6 | David | david69@gmail.com |
| 7 | Shapiro | .shapo@leetcode.com |
输出
| user_id | name | |
|---|---|---|
| 1 | Winston | winston@leetcode.com |
| 3 | Annabelle | bella-@leetcode.com |
| 4 | Sally | sally.come@leetcode.com |
解析
本题的核心在于确定有效表达式的匹配规则, 并写出相应的正则表达式。值得一提的是,在pandas库中自带match()方法支持正则表达式匹配, 无需import re
正则表达式由三部分组成,即前缀、主题和域名
- 前缀以字母开头, 即
^[a-zA-Z] - 主体可以包含字母, 数字,
'_','.','—', 即[a-zA-Z0-9_.—] - 域名为
leetcode@\.com$,\.需要使用反斜杠转义, 在python3.7及以上版本中@无需转义
代码如下:
import pandas as pd
def valid_emails(users: pd.DataFrame) -> pd.DataFrame:
mails = users[users["mail"].str.match(r"^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\.com$")]
return mails
在表达式前应加r表示只读,防止某些字符被转义
此外,Dataframe中的字符型数据以varchar存储,处理时应先转换为str实例

浙公网安备 33010602011771号