【问题标题】:Getting string with second occurrence using regexp_substr in oracle PLSQL在 oracle PLSQL 中使用 regexp_substr 获取第二次出现的字符串
【发布时间】:2022-07-26 23:34:34
【问题描述】:

输入值:

1-> 0055030_1-1-202201060155
2-> 0055040_1-8-202201050155-0501

对应输入的预期输出:

1-> 0055030_1-1
2-> 0055040_1-8

以下 SQL 查询未返回预期输出

select Regexp_substr('0055030_1-1-202201060155', '[^-^]+', 1, 1) from dual;

返回

0055030_1
select Regexp_substr('0055030_1-1-202201060155', '[^-^]+', 1, 2) from dual;

返回

1

我是否需要使用子字符串或任何可以提供所需结果的模式?

【问题讨论】:

  • 是否总是至少有一个 '-' 字符,如果没有,您希望看到什么 - 整个值、null 或其他内容?
  • @AlexPoole,是的,输入字符串中始终至少有两个连字符('-')。

标签: sql oracle regexp-replace


【解决方案1】:

您不需要使用正则表达式,而可以使用 SUBSTRINSTR

WITH
    sample_data (test_str)
    AS
        (SELECT '0055030_1-1-202201060155' FROM DUAL
         UNION ALL
         SELECT '0055040_1-8-202201050155-0501' FROM DUAL)
SELECT test_str, substr(test_str, 1, instr(test_str,'-', 1, 2) - 1) as return_val
  FROM sample_data;


                        TEST_STR     RETURN_VAL
________________________________ ______________
0055030_1-1-202201060155         0055030_1-1
0055040_1-8-202201050155-0501    0055040_1-8

【讨论】:

    【解决方案2】:

    我会使用这个函数的“搜索模式版本”: 从对偶中选择 Regexp_substr('0055030_1-1-202201060155', '(\d*)_(\d)-(\d)');

    模式为:(\d*) 多个数字后跟 下划线、(\d) 一位数字、破折号和一位数字。 如果破折号之间的数字超过一位,则应替换为 '(\d*)_(\d*)-(\d*)'。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-18
      • 2020-10-30
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多