How to select domain name from email address

后端 未结 13 2480
半阙折子戏
半阙折子戏 2020-12-08 02:05

I have email addresses like user1@gmail.com, user2@ymail.com user3@hotmail.com ... etc. I want a Mysql SELECT that will trim user name

13条回答
  •  隐瞒了意图╮
    2020-12-08 02:34

    Using SUBSTRING_INDEX for "splitting" at '@' and '.' does the trick. See documentation at http://dev.mysql.com/doc/refman/5.1/de/string-functions.html#idm47531853671216.

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(email, '@', -1), '.', 1);
    

    Example:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX("foo@bar.buz", '@', -1), '.', 1);
    

    will give you "bar".

    Here is what happens:
    * Split "foo@bar.buz" at '@'. --> ["foo", "bar.buz"]
    * Pick first element from right (index -1). --> "bar.buz"
    * Split "bar.buz" at '.' --> ["bar", "buz"]
    * Pick first element (index 1) --> "bar"
    Result: "bar"

    If you also need to get rid of subdomains, use:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(email, '@', -1), '.', -2), '.', 1);
    

    Example:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX("foo@1.2.3.bar.buz", '@', -1), '.', -2), '.', 1);
    

    will give you "bar".

提交回复
热议问题