【问题标题】:Oracle SQL : Regexp_substrOracle SQL:正则表达式_substr
【发布时间】:2013-07-30 08:11:13
【问题描述】:

我在一列中有以下示例值

Abc-123-xyz
Def-456-uvw
Ghi-879-rst-123
Jkl-abc

预期输出是被'-'分割的第三个元素,如果没有第三个元素,则检索最后一个元素。

请参阅下面的预期输出:

Xyz
Uvw
Rst
Abc

感谢您的帮助。

【问题讨论】:

  • 欢迎来到 Stack Overflow。您可以使用Code Sample {} 工具栏按钮格式化源代码和数据示例。这次我替你做了。
  • 问题标题中不是 regex_substr,oracle 有 regexp_substr
  • 感谢大家的编辑。我的问题接下来会改进。

标签: sql regex oracle


【解决方案1】:
SELECT initcap(nvl(regexp_substr(word, '[^-]+', 1,3),regexp_substr(word, '[^-]+', 1,2)))  FROM your_table;

【讨论】:

  • 感谢您的回答^_^
【解决方案2】:

另一种方法:

SQL> with t1(col) as(
  2    select 'Abc-123-xyz'     from dual union all
  3    select 'Def-456-uvw'     from dual union all
  4    select 'Ghi-879-rst-123' from dual union all
  5    select 'Jkl-Abc'         from dual
  6  )
  7  select regexp_substr( col
  8                      , '[^-]+'
  9                      , 1
 10                      , case
 11                           when regexp_count(col, '[^-]+') >= 3
 12                           then 3
 13                           else regexp_count(col, '[^-]+')
 14                        end
 15                      ) as res
 16    from t1
 17  ;

结果:

RES
---------------
xyz
uvw
rst
Abc

【讨论】:

  • 请注意,REGEXP_COUNT() 仅在 11g 中引入(其他正则表达式函数在 10g 中可用)
【解决方案3】:
regexp_substr(column, '(.*?-){0,2}([^-]+)', 1, 1, '', 2)

【讨论】:

    【解决方案4】:

    你也可以不使用 RegEx:

    with t1 as(
      select 'Abc-123-xyz' as MyText     from dual union all
      select 'Def-456-uvw'     from dual union all
      select 'Ghi-879-rst-123' from dual union all
      select 'Jkl-Abc'         from dual
    )
    SELECT 
      SUBSTR(t1.mytext, LENGTH(t1.mytext) - INSTR(REVERSE(t1.mytext), '-') + 2) 
    FROM t1
    ;
    

    【讨论】:

    • ^ 是的,我的错,我以为他总是想得到最后三个字符...
    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多