【问题标题】:How to get the nth string from the delimited strings using REGEXP_SUBSTR in Oracle如何在 Oracle 中使用 REGEXP_SUBSTR 从分隔字符串中获取第 n 个字符串
【发布时间】:2019-04-11 00:13:11
【问题描述】:

我有一个由# 分隔的字符串,我想要字符串中的第三组/单元格。

例如:

select REGEXP_SUBSTR( 'abc#def##########xyz','[^#]+', 1,1,null) from dual;

输出:abc

select REGEXP_SUBSTR( 'abc#def##########xyz','[^#]+', 1,2,null) from dual;

输出:def

然而

select REGEXP_SUBSTR( 'abc#def##########xyz','[^#]+', 1,3,null) from dual;

输出:xyz

但我期望得到null,因为## 之间的第三个单元格是空的。

【问题讨论】:

    标签: oracle regexp-substr


    【解决方案1】:

    这是a familiar issue。按照该答案的建议使用不同的模式:

    select REGEXP_SUBSTR( 'abc#def##########xyz','(.*?)(#|$)', 1, 1, null, 1) from dual;
    
    abc
    
    select REGEXP_SUBSTR( 'abc#def##########xyz','(.*?)(#|$)', 1, 2, null, 1) from dual;
    
    def
    
    select REGEXP_SUBSTR( 'abc#def##########xyz','(.*?)(#|$)', 1, 3, null, 1) from dual;
    
    (null)
    
    select REGEXP_SUBSTR( 'abc#def##########xyz','(.*?)(#|$)', 1, 12, null, 1) from dual;
    
    xyz
    

    或者使用分层查询(或递归 CTE)一次获取所有这些:

    select level as pos,
      REGEXP_SUBSTR( 'abc#def##########xyz','(.*?)(#|$)', 1, level, null, 1) as result
    from dual
    connect by level <= regexp_count('abc#def##########xyz', '#') + 1;
    
           POS RESULT              
    ---------- --------------------
             1 abc                 
             2 def                 
             3 (null)              
             4 (null)              
             5 (null)              
             6 (null)              
             7 (null)              
             8 (null)              
             9 (null)              
            10 (null)              
            11 (null)              
            12 xyz                 
    
    12 rows selected. 
    

    【讨论】:

    • 非常感谢@alex poole
    【解决方案2】:

    SUBSTR + INSTR 组合怎么样?

    SQL> with test (col) as (select 'abc#def##########xyz' from dual)
      2  select substr(col, instr(col, '#', 1, 2) + 1,
      3                     instr(col, '#', 1, 3) - instr(col, '#', 1, 2) - 1
      4               ) third_string,
      5         --
      6         substr(col, instr(col, '#', 1, 1) + 1,
      7                     instr(col, '#', 1, 2) - instr(col, '#', 1, 1) - 1
      8               ) second_string
      9  from test;
    
    THIRD_STRING    SECOND_STRING
    --------------- ---------------
                    def
    
    SQL>
    

    second_string 解释(一个更简单的情况,因为它实际上返回 something):

    • 第一行INSTR 找到# 字符的第二次出现
    • 第二个INSTR 行查找# 字符的第3 次出现并减去第2 次出现(因此它创建一个子字符串长度)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 2015-10-17
      • 2012-06-26
      • 2021-08-04
      • 2022-01-18
      • 1970-01-01
      • 2022-07-26
      相关资源
      最近更新 更多