Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL: Extracting text between two characters

I have strings that look like

{ABCDE}{F1}
{GHIJ}{K12}

I want to extract the text between the first curly brackets

ABCDE
GHIJ

I tried searching online but a lot of answers seem to be using functions or PL-SQL. Can someone please help me with this?

like image 567
Anish Avatar asked Dec 01 '22 10:12

Anish


2 Answers

We can use REGEXP_SUBSTR here:

SELECT regexp_substr('{ABCDE}{F1}', '\{([^}]+)\}', 1,1,NULL,1) AS output
FROM dual

Demo

This is a less commonly seen use of REGEXP_SUBSTR, which uses a capture group, per this pattern:

\{([^}]+)\}

The sixth parameter says to return the first capture group.

like image 114
Tim Biegeleisen Avatar answered Dec 15 '22 00:12

Tim Biegeleisen


This is old skool. I love regular expressions and can understand them but get into an awful lot of trouble when I try to produce them. A bit like Spanish (for me). So this is just SQL INSTR / SUBSTR / REPLACE. I'm not expecting any upvotes...

WITH test_data (raw_text)
 AS 
  (SELECT '{ABCDE}{F1}' from dual UNION ALL
   SELECT '{GHIJ}{K12}' from dual 
  )
SELECT
 raw_text
,SUBSTR(raw_text,2,INSTR(raw_text,'}{')-2)              first_string
,REPLACE(SUBSTR(raw_text,INSTR(raw_text,'}{')+2),'}')   second_string
--these two from Tim's excellent answer
,regexp_substr(raw_text, '\{([^}]+)\}', 1,1,NULL,1) 
,regexp_substr(raw_text, '\{([^}]+)\}', 1,2,NULL,1)
FROM
 test_data
;

Demo

like image 22
Christian Palmer Avatar answered Dec 14 '22 23:12

Christian Palmer