Reputation: 441
I selected string with uppercase RED and this works good
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
But when I selected with lowercase, I do not get the results I want
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
How can I get results that I would not use in capital letters?
If I wanted to use the function on some rows in the table, I would not get the desired results
Upvotes: 0
Views: 5007
Reputation: 10360
Make sure to add a space before and after your keyword else you'll get BEFORE_STR returned where it is only PART of a word. Here a capture group is used to get the first part where all characters are followed by the case-insensitive keyword surrounded by spaces. Note REGEXP_SUBSTR returns the original string if the match is not found.
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>
Upvotes: 2
Reputation: 272106
You need to specify 'i'
for case-insensitive matching. Having said that, your REGEXP is incorrect... [^(RED]+
will match all characters until one of (
,R
,E
,D
is found.
You could use REGEXP_INSTR
to locate the position of match and SUBSTR
to extract the substring:
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;
Result:
| 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 |
Upvotes: 2