Reputation: 4419
I have a table containing email addresses where some of them contain 'plus' tags - for example,
email
----------------------
[email protected]
[email protected]
[email protected]
I need to be able to query the table and receive the email addresses without the tags:
email
----------------------
[email protected]
[email protected]
[email protected]
Upvotes: 2
Views: 813
Reputation: 4419
This query strips the tag from email addresses on all versions of MySQL:
SELECT IF(LOCATE('+', email) = 0,
email,
CONCAT(
SUBSTRING(email, 1, LOCATE('+', email) - 1),
SUBSTRING(email, LOCATE('@', email))))
FROM my_table;
In English: if there is no +
in the email address, then just use the email address; otherwise, concatenate the text to the left of the +
with the text from the @
to the end of the string.
Upvotes: 1
Reputation: 222582
If you are running MySQL 8.0, you can use regexp_replace()
for this:
select
email,
regexp_replace(email, '\\+[^@].*@+', '@') new_email
from mytable
This phrases as: suppress any sequence of characters starting with '+'
until '@'
. If there is no match, regexp_replace()
leaves the string untouched.
with mytable as (
select '[email protected]' email
union all select '[email protected]'
union all select '[email protected]'
)
select
email,
regexp_replace(email, '\\+[^@].*@+', '@') new_email
from mytable;
| email | new_email |
| ---------------------- | ----------------- |
| [email protected] | [email protected] |
| [email protected] | [email protected] |
| [email protected] | [email protected] |
Upvotes: 2