【问题标题】:How to fetch value between second and third / from string (/ to be consider from right to left)如何从字符串中获取第二个和第三个/之间的值(/从右到左考虑)
【发布时间】:2018-04-01 15:01:29
【问题描述】:

我的要求是从字符串中获取第二个和第三个'/'之间的数据(/ 从右到左考虑),下面是示例。

1.My string is RAM/ESH/BA/BU/MOR/SA and output to be derived is BU
2.My string is RAM/ESH/BA/MOR/SA and output to be derived is BA
3.My String is TR/IV/NI and  output to be derived is TR

请帮我查询。

【问题讨论】:

  • 上一个示例中没有“第三个”/。你的意思是/还是字符串的开头

标签: oracle11g


【解决方案1】:

这是一种方法 - 仅使用标准字符串函数(无正则表达式)以获得最佳性能。注意 INSTR 的使用,其中 -1 作为第三个参数(指示位置);负数表示从字符串末尾开始 AND 计数(从右到左)。

我添加了另外两个输入字符串来测试是否正确处理。如果从右数第二个和第三个 / 之间绝对没有任何内容,则“令牌”必须为 NULL。如果输入字符串中没有至少两个 / 则相同。正如我在评论中解释的那样,您错误地陈述了问题 - 您至少需要在输入中使用两个斜杠;如果只有两个,则从输入字符串的开头获取“令牌”。

with
  inputs ( str ) as (
    select 'RAM/ESH/BA/BU/MOR/SA' from dual union all
    select 'RAM/ESH/BA/MOR/SA'    from dual union all
    select 'TR/IV/NI'             from dual union all
    select 'ST//TUL/SV'           from dual union all
    select 'MOR/SA'               from dual
  )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select str,
       substr( str, instr(str, '/', -1, 3) + 1, 
                    instr(str, '/', -1, 2) - instr(str, '/', -1, 3) - 1
             ) as third_token_from_right
from   inputs;

STR                   THIRD_TOKEN_FROM_RIGHT
--------------------  ----------------------
RAM/ESH/BA/BU/MOR/SA  BU
RAM/ESH/BA/MOR/SA     BA
TR/IV/NI              TR
ST//TUL/SV  
MOR/SA  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多