【问题标题】:REGEXP_SUBSTR desired outputREGEXP_SUBSTR 所需的输出
【发布时间】:2012-11-08 08:31:34
【问题描述】:
SELECT REGEXP_SUBSTR('one,two,three',',[^,]+') AS reg_result FROM DUAL;

REG_RESULT    
,two          

SELECT REGEXP_SUBSTR('eight,nineteen,five',',[^,]+') AS reg_result FROM DUAL;  

REG_RESULT    
,nineteen 

我必须从结果中删除“,”。我也想要最后一个字符串 作为输出。即来自“一、二、三”的 和来自“八、十九、五”的 。 我该怎么做??

【问题讨论】:

    标签: regex oracle oracle11g


    【解决方案1】:

    如果只想获取最后一个单词而不检查您的字符串是否符合特定模式:

    SQL> with t1 as(
      2    select 'one,two,three' as str from dual
      3  )
      4  select regexp_substr(str, '([[:alpha:]]+)$') last_word
      5    from t1
      6  ;
    
    LAST_WORD
    ---------
    three
    

    回复评论

    如何从第一个字符串中获取第二个字符串,从第二个字符串中获取十九个字符串??

    regexp_substr 函数的第四个参数是模式的出现。所以要获取字符串中的第二个单词,我们可以使用regexp_substr(str, '[^,]+', 1, 2)

    SQL> with t1 as(
      2        select 'one,two,three' as str from dual
      3      )
      4  select regexp_substr(str, '[^,]+', 1, 2) as Second_Word
      5       from t1;
    
    Second_Word
    ---------
    two
    

    如果需要从字符串中提取每个单词:

    -- sample of data from your question
    SQL> with t1 as(
      2     select 'one,two,three' as str from dual union all
      3     select 'eight,nineteen,five' from dual
      4  ), -- occurrences of the pattern
      5  occurrence as(
      6   select level as ps
      7     from ( select max(regexp_count(str, '[^,]+')) mx
      8              from t1
      9           ) s
     10    connect by level <= s.mx
     11  ) -- the query
     12  select str
     13       , regexp_substr(str, '[^,]+', 1, o.ps) word
     14       , o.ps as word_num
     15    from t1 t
     16     cross join occurrence o
     17  order by str
     18  ;
    
    STR                  WORD          WORD_NUM
    -------------------  ----------- ----------
    eight,nineteen,five  eight                1
    eight,nineteen,five  nineteen             2
    eight,nineteen,five  five                 3
    one,two,three        three                3
    one,two,three        one                  1
    one,two,three        two                  2
    
    6 rows selected
    

    【讨论】:

    • 感谢您的回复。如何从第一个字符串 two 和第二个字符串 nineteen 获取字符串??
    【解决方案2】:
    SELECT REGEXP_SUBSTR(REGEXP_SUBSTR('one,two,three',',[^,]+$'),'[^,]+') AS reg_result FROM DUAL;
    

    我不确定 Oracle 是否有lookbehinds,但你也可以试试这个:

    SELECT REGEXP_SUBSTR('one,two,three','(?<=,)[^,]+$') AS reg_result FROM DUAL;
    

    【讨论】:

    • SELECT REGEXP_SUBSTR('one,two,three','[^,]+$') AS reg_result FROM DUAL; REG_RESULT three 删除第一个逗号。感谢您的答复。我的第一个查询呢??
    • @sam 我发布的答案解决了这两个问题。看这个演示:sqlfiddle.com/#!4/d41d8/4497/0
    猜你喜欢
    • 2021-06-17
    • 2021-01-30
    • 1970-01-01
    • 2017-09-08
    • 2022-01-01
    • 2023-04-04
    • 2014-05-06
    • 2013-10-16
    • 2021-05-24
    相关资源
    最近更新 更多