metadaddy
metadaddy

Reputation: 4419

How do I remove 'plus' tags from email addresses in a MySQL query?

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

Answers (2)

metadaddy
metadaddy

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

GMB
GMB

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.

Demo on DB Fiddle:

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

Related Questions