简体   繁体   中英

oracle (12c) regexp_substr to split filename and directoryname

Using Oracle 12c, I'd like to split string containing full filename (including directory) to 2 strings : first one with the directory, second with the filename.

I already got filename but can't extract directory correctly :

select
   val,
   regexp_substr(val, '[^/]+/[^/]+', 1, 1) as dirname,
   regexp_substr(val, '[^/]+$', 1, 1) as filename
from (select '/a/b/c/d/e/f/file.ext' as val from dual) t

This gives:

dirname = a/b -- This is my purpose...
filename = file.ext -- This is correct !

I'd like to get dirname as

/a/b/c/d/e/f

including the 1st "/"

NB : I don't want to split into several lines (using connect by sentence). I need to get one row with 2 seperate strings...

Thanks...

We can try using REGEXP_SUBSTR and REGEXP_REPLACE as follows:

SELECT
    REGEXP_REPLACE(val, '/[^/]*$', '') AS path,
    REGEXP_SUBSTR(val, '[^/]+$') AS filename
FROM yourTable;

The basic strategy here is to remove the final slash and all proceeding it to obtain the directory path, and do the opposite to obtain the filename.

You don't need (slow) regular expressions and can just use SUBSTR and INSTR :

Oracle Setup :

CREATE TABLE test_data ( val ) AS
  SELECT '/a/b/c/d/e/f/file.ext' FROM DUAL;

Query :

SELECT SUBSTR( val, 1, INSTR( val, '/', -1 ) ) AS dir,
       SUBSTR( val, INSTR( val, '/', -1 ) + 1 ) AS filename
FROM   test_data;

Output :

\nDIR |  FILENAME \n:------------ |  :------- \n/a/b/c/d/e/f/ |  file.ext \n

db<>fiddle here

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