简体   繁体   中英

Extracting specific part of column values in Oracle SQL

I want to extract a specific part of column values. The target column and its values look like

TEMP_COL
---------------
DESCOL 10MG
TEGRAL 200MG 50S
COLOSPAS 135MG 30S

The resultant column should look like

RESULT_COL
---------------
10MG
200MG
135MG

This can be done using a regular expression:

SELECT regexp_substr(TEMP_COL, '[0-9]+MG')
FROM the_table;

Note that this is case sensitive and it always returns the first match.

I would probably approach this using REGEXP_SUBSTR() rather than base functions, because the structure of the prescription text varies from record to record.

SELECT TRIM(REGEXP_SUBSTR(TEMP_COL, '(\s)(\S*)', 1, 1))
FROM yourTable

The pattern (\\s)(\\S*) will match a single space followed by any number of non-space characters. This should match the second term in all cases. We use TRIM() to remove a leading space which is matched and returned.

how do you know what is the part you want to extract? how do you know where it begins and where it ends? using the white-spaces?

if so, you can use substr for cutting the data and instr for finding the white-spaces.

example:

select substr(tempcol, -- string
              instr(tempcol, ' ', 1), -- location of first white-space 
              instr(tempcol, ' ', 1, 2) - instr(tempcol, ' ', 1))  -- length until next space
from dual

another solution is using regexp_substr (but it might be harder on performance if you have a lot of rows):

SELECT REGEXP_SUBSTR (tempcol, '(\S*)(\s*)', 1, 2)
FROM dual;

edit: fixed the regular expression to include expressions that don't have space after the parsed text. sorry about that.. ;)

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