PL/SQL按模式拆分字符串

3
与这个问题类似... 我试图使用正则表达式来分割以下字符串:

如何使用正则表达式将一个字符串分割成多个子串?

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+)(.?$)))

我在几个正则表达式网站和这篇文章上找了一下,但没有太多的进展。请问有人能帮忙吗? 提取使用正则表达式分隔符分隔的文本某部分

Oracle不支持正则表达式中的非捕获组或前瞻。 - MT0
2个回答

4
这是一个简单的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

本文介绍了如何将逗号分隔的字符串拆分并传递给SELECT语句的IN子句。其中提到使用正则表达式、模式匹配和循环来实现,可以用于处理多个值的查询。此外,还给出了在Oracle数据库中实现该功能的示例代码。

0

你的所需输出有两个问题。第一个问题是如何定义要排除的标记(例如“on”,“at”等)。第二个问题是如何忽略某些标记中的空格(例如“电力公司”,“电影票”)。

通过两步过程很容易解决第一个问题。第一步在空格上拆分字符串,第二步删除不需要的标记:

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
 ;

这里是一个 SQL Fiddle 演示

第二个问题比较难解决。我猜你需要另一个查找表来识别铃声,并可能使用 listagg() 来连接它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接