首页 > 解决方案 > 正则表达式匹配 MySQL 中的重复/别名电子邮件

问题描述

我正在尝试提出一些正则表达式来检查数据库中是否存在电子邮件。这里更具体的是,我想找到相同但可能写法不同的电子邮件。eg与和john.doe@example.com相同。johndode+123@example.comj.o.h.n.d.o.e@example.com

使用另一个脚本,我删除了所有的点和文本,+这样 john.doe+123@example.com就变成了johndoe@example.com. 如何使用这个“剥离”地址来匹配它在 MySQL 数据库中的别名?

我对 RegEx 几乎没有经验,而且我之前也没有真正将它与 SQL 一起使用过。无论如何,我只能想出以下代码:

RegEx(匹配@ 符号之前的+<any text>所有内容.

(\+.*(?=@)|\.(?=.*@))

SQL

SELECT email FROM users WHERE email REGEXP '(\+.*(?=@)|\.(?=.*@))'
//or
SELECT * from users WHERE email REGEXP_LIKE('johndoe@example.com', '(\+.*(?=@)|\.(?=.*@))')

我得到以下两个错误:

#1064 - 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以了解在附近使用的正确语法REGEXP_LIKE('johndoe@example.com', '(\+.*(?=@)|\.(?=.*@))')

我想做的是select email from users where email = 'johndoe@example.com' but disregard these characters (\+.*(?=@)|\.(?=.*@)
(代码作为准备好的语句执行)

任何提示或建议将不胜感激!

标签: mysqlsqlregexmysql-regexp

解决方案


在 MySQL 中,最简单的方法可能是将问题分解为用户名和域:

where replace(substring_index(substring_index(email, '@', 1), '+', 1), '.', '') = substring_index('johndoe@example.com', '@', 1) and
      substring_index(email, '@', -1) = substring_index('johndoe@example.com', '@', -1) and
      email like '%@%' and
      email not like '%@%@%'

推荐阅读