如何从Oracle中2个单词之间的字符串中提取文本

时间:2018-11-02 14:44:18

标签: oracle

我想从字符串中获取2个单词之间的文本。 GROUP TITLEGROUP TITLEDURATION之间 Group Title: Goal Setting Duration: 60 minute 我希望结果在单独的列中,而DURATION在另一列中。

我正在使用以下内容,但它在字符串中的位置不一致,因此当我使用以下内容时,会得到部分附加文本

CASE WHEN A.NOTE_TEXT like 'Group Title:%' 
then SUBSTR(A.NOTE_TEXT,INSTR(A.NOTE_TEXT,'Group Title:',1),55) END AS GROUP_TITLE,*

我的结果看起来像

GROUP TITLE                   |  DURATION
Group Title: Goal Setting     |  Duration: 60 minutes      
Group Title: Mood Management  |  Duration: 90 minutes

如何仅获取GROUP TITLEGROUP TITLE: TITLE OF GROUP REPORT的{​​{1}}列的文本?

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

3 个答案:

答案 0 :(得分:2)

我相信这就是您想要的。正则表达式使用捕获组来“记住”锚定文本之间的内容并返回它。

SQL> with tbl(str) as (
     select 'Group Title: Goal Setting Duration: 60 minutes'    from dual union all
     select 'Group Title: Mood Management Duration: 90 minutes' from dual
   )
   select regexp_substr(str, 'Group Title:\s(.*?)\sDuration.*', 1, 1, NULL, 1) "GROUP TITLE",
          regexp_substr(str, '.*Duration:\s(.*?)( |$)', 1, 1, NULL, 1) "DURATION"
   from tbl;

GROUP TITLE        DURATION
-----------------  -----------------
Goal Setting       60 minutes
Mood Management    90 minutes

SQL>

编辑仅当标题更改时,这些正则表达式才在冒号上定界:

select regexp_substr(str, '.*:\s(.*?)\s.*:.*', 1, 1, NULL, 1) "GROUP TITLE",
       regexp_substr(str, '.*:\s(.*?)( |$)', 1, 1, NULL, 1) "DURATION"
from tbl;
再次进行下一步,如果您认为这实际上只是一个定界字符串,并且定界符是一个空格,单词,冒号,空格,请捕获并返回第二组和第三组字符,后跟一个空格,单词,冒号或行尾。

select regexp_substr(str, '(.*?)( \w+: |$)', 1, 2, NULL, 1) "GROUP TITLE",
       regexp_substr(str, '(.*?)( \w+: |$)', 1, 3, NULL, 1) "DURATION"
from tbl;

答案 1 :(得分:0)

下面的查询分别获取组标题和持续时间:

 select regexp_substr(regexp_substr(regexp_replace ('Group Title: Goal Setting ------------ Duration: 60 minutes','\-+','-'),'[^-]+',1,1),'[^:]+',1,2)  "Group Title" from dual;

 select regexp_substr(regexp_substr(regexp_replace ('Group Title: Goal Setting ------------ Duration: 60 minutes','\-+','-'),'[^-]+',1,2),'[^:]+',1,2) "Duration" from dual;

如果希望使用以下查询,请使用以下查询:

select regexp_substr('Group Title: Discharge and Reintegration Duration: 60 minute','[^:]+',1,2) "Group Title" from dual

  select regexp_substr('Group Title: Discharge and Reintegration Duration: 60 minute','[^:]+',1,3)  "Group Title" from dual

答案 2 :(得分:0)

这很好用!!

SQL> with tbl(str) as (
     select 'Group Title: Goal Setting Duration: 60 minutes'    from dual union all
     select 'Group Title: Mood Management Duration: 90 minutes' from dual
   )
   select regexp_substr(str, 'Group Title:\s(.*?)\sDuration.*', 1, 1, NULL, 1) "GROUP TITLE",
          regexp_substr(str, '.*Duration:\s(.*?)( |$)', 1, 1, NULL, 1) "DURATION"
   from tbl;

GROUP TITLE        DURATION
-----------------  -----------------
Goal Setting       60 minutes
Mood Management    90 minutes

SQL>