简体   繁体   中英

How to get first name,last name,provider from a email address in Oracle sql

I try to get first name, last name, provider from an email address "ben.ghol@gmail.com" but it doesn't work.

Table emailtable. My code here:

     select 
        SUBSTR(email,1, INSTR(email,'.')-1) as firstname,
        SUBSTR(email,INSTR(email,'.')+1, INSTR(email,'@')-1) as lastname,
        SUBSTR(email,INSTR(email,'@')+1,INSTR(email,'.')-1) as "provider"
        from emailtable;

The third argument for SUBSTR is the length of the substring (and not the position of the end character).

You can use a nested sub-query to find the position of the separators and then use those values in SUBSTR in the outer query:

SELECT SUBSTR(email, 1, name_separator - 1) AS first_name,
       SUBSTR(email, name_separator + 1, at_separator - name_separator - 1)
         AS last_name,
       SUBSTR(email, at_separator + 1, domain_separator - at_separator - 1)
         AS domain
FROM   (
  SELECT email,
         INSTR(email, '.') AS name_separator,
         INSTR(email, '@') AS at_separator,
         INSTR(email, '.', INSTR(email, '@')) AS domain_separator
  FROM   emailtable
)

Which, for the sample data:

CREATE TABLE emailtable ( email ) AS
SELECT 'ben.ghol@gmail.com' FROM DUAL;

Outputs:

FIRST_NAME LAST_NAME DOMAIN
ben ghol gmail

db<>fiddle here

You can use regexp_substr() :

select regexp_substr(email, '^[^.]+') as firstname,
       regexp_substr(email, '[^.@]+', 1, 2) as lastname,
       regexp_+substr(email, '[^@]+$') as provider
from (select 'ben.ghol@gmail.com' as email from dual) x;

Here is a db<>fiddle.

SUBSTR takes 3 parameters: input string, start position and length of substring.

You appear to be using end position as the 3rd parameter.

You can get the length to use as the 3rd parameter by doing (end position - start position + 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM