【问题标题】:Locate a sub-string within a string Oracle在字符串 Oracle 中查找子字符串
【发布时间】:2025-11-23 15:50:01
【问题描述】:

我正在尝试在字符串中定位子字符串。我在网上找到的所有东西都在定位它的位置。我不关心位置,给定每行浮动的位置,我不能说 regexp_instr(X, 10, 5)。

我想说如果 X in Column String 然后给我一个新列,其中只有我要求的字符串。如果不给我Y。

问题是 10 个字符串中有 1 个在 Column String 中,我正尝试分 1 到 2 个步骤将它们提取为单独的列。

这可以吗? 谢谢。

【问题讨论】:

  • 使用类似Select case when instr('CAT','A')>0 then 'A' else 'Not in' end from dual; 的案例陈述或添加一些具有预期结果的示例来帮助我们理解问题。

标签: string oracle substring proc-sql


【解决方案1】:

也许像... 但我不清楚您是想要一列、多列还是想要第一个结果或所有匹配的结果...

如果列包含“CAT”并且您正在寻找 Z、C、A、T... 结果列中应该有什么结果?没有 Z...只有 C 或 CAT 还是什么?

SELECT CASE WHEN INSTR('CAT','Z')>0 THEN 'Z' 
            WHEN INSTR('CAT','C')>0 THEN 'C'
            WHEN INSTR('CAT','A')>0 THEN 'A'
            WHEN INSTR('CAT','T')>0 THEN 'T'
            ELSE 'Not in' end from dual;

【讨论】:

    【解决方案2】:

    要在一个字符串中搜索另一个字符串并在找到时返回搜索到的字符串,如果没有找到则返回固定字符串,您有多种选择。 instr 和 regexp_instr 方法依赖于这样一个事实,即在未找到时它们返回零 (0) 索引,而 regexp_substr 方法在未找到时返回 null,否则返回与搜索模式匹配的字符串:

    with dta as (
      select 'this is a test' str from dual union all
      select 'every good boy does fine' from dual union all
      select 'testing one two three' from dual
    ), fnd as (
      select 'test' fnd, 'not found' fail from dual union all
      select 'good' fnd, 'not good' fail from dual
    )
    select fnd
         , str
         , case instr(str, fnd) when 0 then fail else fnd end result
         , case regexp_instr(str,fnd) when 0 then fail else fnd end result2
         , nvl(regexp_substr(str, fnd), fail) result3
      from dta, fnd
      order by 1, 2;
    

    【讨论】: