簡體   English   中英

REGEXP_SUBSTR() 在字符串之前選擇

[英]REGEXP_SUBSTR() select before string

我選擇了大寫紅色的字符串,這很好用

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

如何獲得我不會使用大寫字母的結果?

如果我想在表中的某些行上使用該函數,則不會得到所需的結果

您需要為不區分大小寫的匹配指定'i' 話雖如此,您的 REGEXP 不正確... [^(RED]+將匹配所有字符,直到找到( , R , E , D

您可以使用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       |

確保在關鍵字之前和之后添加一個空格,否則您將得到 BEFORE_STR 返回,其中它只是單詞的一部分。 這里使用捕獲組來獲取第一部分,其中所有字符后跟由空格包圍的不區分大小寫的關鍵字。 注意 REGEXP_SUBSTR 如果未找到匹配項,則返回原始字符串。

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM