0

I'm working on a substring regular expression and I need to get all characters from a string like this:

FIRSTCOLUMN, SECONDCOLUMN, THIRDCOLUMN

So far I've got:

SELECT 
    REGEXP_SUBSTR('FIRSTCOLUMN, SECONDCOLUMN, THIRDCOLUMN', '[^SECONDCOLUMN]+') AS SUBSTRING 
FROM DUAL;

This returns just "FIR" but I need the result to be "FIRSTCOLUMN, ".

Another example to understand better the question is: when I have '[^THIRDCOLUMN]+' pattern instead of '[^SECONDCOLUMN]+' as the first example, I want the result to be "FIRSTCOLUMN, SECONDCOLUMN, ".

I know it is possible but I'm not good enough on regular expressions.

1 Answer 1

2

You are getting basic regular expressions concepts wrong. The [^...] negates all characters inside the class, so it looks for characters not S, not E, not C, etc which correctly stops at FIRST (see the S).
What you possibly want is a lazy quantifier:

^.*?SECONDCOLUMN

or

^.*?THIRDCOLUMN

respectively.

Sign up to request clarification or add additional context in comments.

2 Comments

Technically, you need some syntactic sugar to exclude the delimiting string from being part of the result: either wrap it with a replace(..., 'secondcolumn') or use select regexp_substr ( 'firstcolumn, secondcolumn, thirdcolumn', '^(.*?)secondcolumn', 1, 1, null, 1 ) from dual; The additional arguments denote match offset, occurrence, match parameters, capture group to be returned (oracle 12c only). Consult oracle docs for detailed info. If any term is double dutch to you, consider to take a tour to a site explaining regexen (eg. regular-expressions.info).
@Jan Thanks for the suggestion. But I wanted to exclude the SECONDCOLUMN string of the first example. So, using your suggestion, my code became: SELECT REGEXP_SUBSTR('FIRSTCOLUMN, SECONDCOLUMN, THIRDCOLUMN', '^.*?SECONDCOLUMN') AS SUBSTRING FROM DUAL; But my result is: FIRSTCOLUMN, SECONDCOLUMN In my case I wanted the result to be: FIRSTCOLUMN, ** That's why I put the '[^...]', to exculde "SECONDCOLUMN" from "FIRSTCOLUMN, **SECONDCOLUMN" . Thank you in advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.