【问题标题】:PL/SQL Split string by patternPL/SQL 按模式拆分字符串
【发布时间】:2018-11-10 23:36:08
【问题描述】:

类似于这个问题...

How can I use regex to split a string, using a string as a delimiter?

...我正在尝试拆分以下字符串:

Spent 30 CAD in movie tickets at Cineplex on 2018-06-01

我想要的输出是这样的:

ELEMENT ELEMENT_VALUE
------- -------------
      1 Spent
      2 30
      3 CAD
      4 movie tickets
      5 Cineplex
      6 2018-06-01

同理,应该可以处理:

Paid 600 EUR to Electric Company

制作:

ELEMENT ELEMENT_VALUE
------- -------------
      1 Paid
      2 600
      3 EUR
      4 
      5 Electric Company

我试过这个正则表达式无济于事:

(\w+)(\D+)(\w+)(?(?=in)(\w+)(at)(\w+)(on)(.?$)|((?=to)(\w+)(.?$)))

我查看了几个正则表达式网站以及这篇文章,但运气不佳:

Extract some part of text separated by delimiter using regex

有人可以帮忙吗?

【问题讨论】:

  • Oracle 不支持非捕获组或正则表达式中的前瞻。

标签: regex oracle plsql regexp-substr


【解决方案1】:

这是一个简单的 SQL 分词器,它在空格处中断:

select regexp_substr('Spent 30 CAD in movie tickets at Cineplex on 2018-06-01','[^ ]+', 1, level) from dual
connect by regexp_substr('Spent 30 CAD in movie tickets at Cineplex on 2018-06-01', '[^ ]+', 1, level) is not null

发件人:https://blogs.oracle.com/aramamoo/how-to-split-comma-separated-string-and-pass-to-in-clause-of-select-statement

【讨论】:

    【解决方案2】:

    您需要的输出有两个问题。首先是如何定义要排除的标记('on'、'at' 等)。二是如何忽略某些token中的空格('电力公司','电影票')。

    通过两步过程解决第一点很容易。步骤 #1 将字符串拆分为空格,步骤 #2 删除不需要的标记:

    with exclude as (
      select 'in' as tkn from dual union all
      select 'at' as tkn from dual union all
      select 'to' as tkn from dual union all
      select 'on' as tkn from dual 
      )
      , str as (
        select id
               , level as element_order
               , regexp_substr(txt, '[^ ]+', 1, level) as tkn
        from t23
        where id = 10
        CONNECT BY level <= regexp_count(txt, '[^ ]+')+1
        and id = prior id
        and prior sys_guid() is not null
        )
     select row_number() over (partition by str.id order by str.element_order) as element
           , str.tkn as element_value
     from str
          left join exclude on exclude.tkn = str.tkn
     where exclude.tkn is null
     and str.tkn is not null
     ;
    

    这里是a SQL Fiddle demo。

    第二点很难解决。我想您需要另一个查找表来识别振铃器,并且可能使用listagg() 来连接它们。

    【讨论】:

      猜你喜欢
      • 2013-02-05
      • 2021-01-06
      • 2013-04-11
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 2022-07-12
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多