第一次遇到使用正则表达式的SQL题目,正则表达式在之前的Python提取文本的文章中也有提到。
使用方法
MySQL中正则关键字regexp
(正则扩展),用法:where col_name regexp ‘正则表达式’。
题目:查询有效账户
写一条 SQL 语句,查询拥有有效邮箱的用户。
有效的邮箱包含符合下列条件的前缀名和域名:
- 前缀名是包含字母(大写或小写)、数字、下划线 ‘_’、句点 ‘.’ 和/或横杠 ‘-’ 的字符串。前缀名必须以字母开头。
- 域名是 ‘@leetcode.com’ 。
- 按任意顺序返回结果表。
查询格式如下所示:
Users
+---------+-----------+-------------------------+
| user_id | name | mail |
+---------+-----------+-------------------------+
| 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 | mail |
+---------+-----------+-------------------------+
| 1 | Winston | winston@leetcode.com |
| 3 | Annabelle | bella-@leetcode.com |
| 4 | Sally | sally.come@leetcode.com |
+---------+-----------+-------------------------+
2 号用户的邮箱没有域名。
5 号用户的邮箱包含非法字符 #。
6 号用户的邮箱的域名不是 leetcode。
7 号用户的邮箱以句点(.)开头。
答案
SELECT
*
FROM
Users
WHERE mail REGEXP '^[a-zA-Z]+[a-zA-Z0-9_\\.\\-]*@leetcode.com$';
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-users-with-valid-e-mails