REGEXP_SUBSTR()在字符串前选择

时间:2018-11-27 12:44:47

标签: sql regex string oracle

我选择了大写红色的字符串,效果很好

SQL> WITH DATA AS
  2   ( SELECT 'we saw a RED apple on the big tree' str FROM dual)
  3  SELECT str,
  4  REGEXP_SUBSTR(str, '[^(RED]+') before_str
  5  FROM data;
STR                                BEFORE_STR
---------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------
we saw a RED apple on the big tree we saw a

但是当我选择小写字母时,我没有得到想要的结果

SQL> WITH DATA AS
  2  ( SELECT 'we saw a red apple on the big tree' str FROM dual)
  3  SELECT str,
  4  REGEXP_SUBSTR(str, '[^(red]+') before_str
  5  FROM data;

STR                                BEFORE_STR
---------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------
we saw a red apple on the big tree w

如何获得我不会用大写字母显示的结果?

如果我想在表中的某些行上使用该功能,我将无法获得预期的结果

2 个答案:

答案 0 :(得分:2)

您需要指定'i'用于不区分大小写的匹配。话虽如此,您的REGEXP不正确... [^(RED]+将匹配所有字符,直到找到(RED中的一个为止。 / p>

您可以使用REGEXP_INSTR来定位匹配位置,并使用SUBSTR来提取子字符串:

WITH DATA AS( 
    SELECT 'we saw a red apple on the big tree' str FROM dual UNION ALL
    SELECT 'we saw a RED apple on the big tree' str FROM dual UNION ALL
    SELECT 'we saw something' str FROM dual
)
SELECT str, SUBSTR(str, 1, REGEXP_INSTR(str, 'RED', 1, 1, 0, 'i') - 1) before_str
FROM data;

结果:

| STR                                | BEFORE_STR |
|------------------------------------|------------|
| we saw a red apple on the big tree | we saw a   |
| we saw a RED apple on the big tree | we saw a   |
| we saw something                   | NULL       |

答案 1 :(得分:1)

请确保在关键字前后添加一个空格,否则您将获得BEFORE_STR返回,该单词仅是单词的一部分。在这里,捕获组用于获取所有字符后跟空格的不区分大小写的关键字的第一部分。注意如果找不到匹配项,则REGEXP_SUBSTR返回NULL。

SQL> WITH DATA(str) AS(
       SELECT 'we saw a red apple on the big tree' FROM dual UNION ALL
       SELECT 'we saw a RED apple on the big tree' FROM dual UNION ALL
       SELECT 'we saw something'                   FROM dual UNION ALL
       SELECT 'we saw a redbird on the big tree'   FROM dual
   )
   SELECT str, REGEXP_SUBSTR(str, '^(.*?)( RED )', 1, 1, 'i', 1) before_str
   FROM data;

STR                                BEFORE_STR
---------------------------------- ----------------------------------
we saw a red apple on the big tree we saw a
we saw a RED apple on the big tree we saw a
we saw something
we saw a redbird on the big tree

SQL>