0

Please help to define Postgres regexp for this case:

I have string field:

union all select 'AbC-345776-2345' /*comment*/ union all select 'Fgr-sdf344-111a' /*BN34*/ some text union all select 'sss-sdf34-123' /*some text*/ some text

Here is the same text in select statement for convinience:

select 'union all select ''AbC-345776-2345'' /*comment*/ union all select ''Fgr-sdf344-111a'' /*BN34*/ some text union all select ''sss-sdf34-123'' /*some text*/ some text' as str

I need to get from this mess text only values in '...' and select it into separated rows like this:

AbC-345776-2345
Fgr-sdf344-111a
sss-sdf34-123

Pattern: 'first 2-3 letters - several letters and numbers - several letters and numbers'

I created this select but it contains all comments and "sometext" as well:

select regexp_split_to_table(trim(replace(replace(replace(replace(t1.str,'union all select',''),'from DUAL',''),chr(10),''),'''','') ), E'\\s+')
from (select 'union all select ''AbC-345776-2345'' /*comment*/ union all select ''Fgr-sdf344-111a'' /*BN34*/ some text union all select ''sss-sdf34-123'' /*some text*/ some text' as str) t1; 

1 Answer 1

1

The following should do it:

select (regexp_matches(str, $$'([a-zA-Z]{2,3}-[a-zA-Z0-9]+-[a-zA-Z0-9]+)'$$, 'g'))[1]
from the_table;

Given your sample data it returns:

regexp_matches 
---------------
AbC-345776-2345
Fgr-sdf344-111a
sss-sdf34-123  

The regex checks for the pattern you specified inside single quotes. By using a group (...) I excluded the single quotes from the result.

regexp_matches() returns one row for each match, containing an array of matches. But as the regex only contains a single group, the first element of the array is what we are interested in.

I used dollar quoting to avoid escaping the single quotes in the regex

Online example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.