【问题标题】:Split string by delimiter in Oracle with regular expressions使用正则表达式在Oracle中按分隔符拆分字符串
【发布时间】:2019-02-25 15:43:00
【问题描述】:

我需要在 Oracle 中编写脚本以在查询中按 / 字符拆分字符串“BP/593/00294”和“NC//12345”,以便在不同的列中包含值。

我在想这样的事情:

select regexp_substr(mystr, '[^/]+') as col1, 
regexp_substr(c.usertext21,'[^/]+',1,2) as col2
from mytable

但在 col2 中,我从第二个字符串中丢失了空字符串值。 我需要保留两个字符串中的每个值。结果应该是这样的:

<table>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<tr>
  <td>BP</td>
  <td>593</td>
  <td>00294</td>
</tr>
<tr>
  <td>NC</td>
  <td></td>
  <td>12345</td>
</tr>
</table>

任何帮助将不胜感激。 谢谢

【问题讨论】:

    标签: regex oracle plsql


    【解决方案1】:

    您可以在字符串开头或/ 之后捕获除/ 之外的0 个或多个字符:

    select 
      regexp_substr('BP/593/00294', '(^|/)([^/]*)') as col1,
      regexp_substr('BP/593/00294', '(^|/)([^/]*)', 1, 2, null, 2)  as col2,
      regexp_substr('BP/593/00294', '(^|/)([^/]*)', 1, 3, null, 2)  as col3
    from dual
    

    请参阅online demo

    详情

    • (^|/) - 捕获组 1:字符串开头或 /
    • ([^/]*) - 捕获组 2:除 / 之外的任何 0 个或多个字符。

    注意提取第 2 组值的 2 参数。请参阅regex demo

    【讨论】:

    • 像魅力一样工作!非常感谢!
    【解决方案2】:

    如果要捕获的拆分数量未知,并且希望每个拆分为单独的行,则可以使用 connect by 子句:

    with example as (
       select 'NC//12345/12qwe/////12sadf' text from dual
    )
     select regexp_substr(e.text, '[^/]+', 1, LEVEL) col
       from example e
    connect by regexp_instr(e.text, '[/]+', 1, LEVEL - 1) > 0
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 2014-11-22
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多