![](/img/trans.png)
[英]How to get everything in a string up to the 2nd or 3rd comma in postgresql?
[英]Get value between 2nd and 3rd comma
我试图从所有内容都在一个列中的地址中提取状态,这是一个示例:
2901 MAIN ST,CORNING,NY,14830
我一直在尝试找出如何将substr
和instr
一起使用,但是我似乎无法理解instr
的instr
。 这是我到目前为止的内容:
select substr('hello,hello,NY,11725-1234',1,instr('hello,hello,NY,11725-1234',',',2,3))
from dual;
我以为它会在第二个逗号开始,在第三个逗号结束,并让我的所有内容介于两者之间,但事实并非如此。
任何帮助表示赞赏。
select
regexp_substr('2901 MAIN ST,CORNING,NY,14830', '(.*?,){2}(.*?),', 1, 1, '', 2)
from dual
一般来说,
n_th_component :=
regexp_substr(string, '(.*?,){'||(n-1)||'}([^,]*)', 1, 1, '', 2);
例:
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)
正则表达式是执行此类操作的好方法。 SUBSTR和INSTR也可以使用,但是通过利用INSTR的第4个参数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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.