Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a string after pattern PostgreSQL

So I have a column like the following:

diagnosis

715.16 oSTEOARTHRITIS, LOWER-LEG 
715.17 - OSTEOARTHRITIS, ANKLE AND FOOT
715.90 oSTEOARTHRITIS, UNSPECIFIED
716.10 - TRAUMATIC ARTHROPATHY - UNSPECIFIED

Some entries have initial dashes, some do not. Some have dashes later in the string.

I'd like to select the substring (in itallics) with the pattern:

(any chars)(dash)(space)(any alphanumeric)(the rest of the string)

OR

(any chars)(space)(any alphanumeric)(the rest of the string)

My query goes: select substring(diagnosis from '% #"\w%#"' for '#') from TableICDdict;

but it just returns all the rows with empty strings in them (no errors). Any ideas on how to actually output the extracted substrings?

Thanks

like image 637
GotYaNumba Avatar asked Sep 09 '26 09:09

GotYaNumba


1 Answers

Use regexp_replace() to skip all characters preceding first space (and the space) and ltrim() to skip additional '- ' strings:

with t(diagnosis) as (values 
    ('715.16 oSTEOARTHRITIS, LOWER-LEG'),
    ('715.17 - OSTEOARTHRITIS, ANKLE AND FOOT'),
    ('715.90 oSTEOARTHRITIS, UNSPECIFIED'),
    ('716.10 - TRAUMATIC ARTHROPATHY - UNSPECIFIED'))
select ltrim(regexp_replace(diagnosis, '.*? (.*)', '\1'), '- ') result
from t;

               result                
-------------------------------------
 oSTEOARTHRITIS, LOWER-LEG
 OSTEOARTHRITIS, ANKLE AND FOOT
 oSTEOARTHRITIS, UNSPECIFIED
 TRAUMATIC ARTHROPATHY - UNSPECIFIED
(4 rows)
like image 76
klin Avatar answered Sep 10 '26 23:09

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!