I am trying to extract the state from an address where everything is in one column, heres an example:
2901 MAIN ST,CORNING,NY,14830
I have been trying to figure out how to do it with the substr
and instr
together, but I cant seem to get the hang of instr
. Here is what I have so far:
select substr('hello,hello,NY,11725-1234',1,instr('hello,hello,NY,11725-1234',',',2,3))
from dual;
I thought it would start at the second comma and end at the 3rd and get my everything in between, but that doesnt seem to be the case.
Any help is appreciated.
select
regexp_substr('2901 MAIN ST,CORNING,NY,14830', '(.*?,){2}(.*?),', 1, 1, '', 2)
from dual
In general,
n_th_component :=
regexp_substr(string, '(.*?,){'||(n-1)||'}([^,]*)', 1, 1, '', 2);
Example:
select
n,
regexp_substr('2901 MAIN ST,CORNING,NY,14830',
'(.*?,){'||(n-1)||'}([^,]*)', 1, 1, '', 2)
from (select level n from dual connect by level <= 4)
Regular expressions are a great way to do this sort of thing. SUBSTR and INSTR can also be used, however, by taking advantage of the 4th parameter of INSTR, nth_appearance
:
select INSTR(mystring,',',1,1) AS first_comma
,INSTR(mystring,',',1,2) AS second_comma
,SUBSTR(mystring
,INSTR(mystring,',',1,1) + 1
,INSTR(mystring,',',1,2)
- INSTR(mystring,',',1,1)
- 1)
AS middle_bit
FROM
(select 'hello,world,NY,11725-1234' as mystring from dual);
FIRST_COMMA SECOND_COMMA MIDDLE_BIT
=========== ============ ==========
6 12 world
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.