Reputation: 19
Using oracle, how to get a specific word before a word. i got a sample script that i found here but its in reverse(it gets the word after a specific word which is the CITY)
select regexp_substr ('TEXAS CITY CALIFORNIA', 'CITY[[:space:]]([[:alpha:]]+)', 1, 1, NULL, 1 test from dual;
result: CALIFORNIA
what i want is to get is texas, but i need a dynamic script.
Upvotes: 0
Views: 1160
Reputation: 35900
Efficient way to achieve the desired result is to use substr
and instr
as follows:
substr('TEXAS CITY, CALIFORNIA',1, instr('TEXAS CITY, CALIFORNIA',' CITY'))
Upvotes: 1
Reputation: 21
Assuming that "CITY" won't always be the second word, this will get you only the word immediately preceding "CITY" for any string.
select regexp_substr (regexp_substr('TEXAS CITY, CALIFORNIA', '([[:alpha:]]+)[[:space:]]CITY', 1), '^[^ ]+', 1)test from dual
For more information, check out how regex works in Oracle SQL.
https://docs.oracle.com/cd/B12037_01/appdev.101/b10795/adfns_re.htm
Upvotes: 0
Reputation: 15893
You can extract first word from any sentence with below code:
select regexp_substr ('TEXAS CITY, CALIFORNIA', '^[^ ]+',1 )test from dual;
Upvotes: 0