Thursday, April 27, 2017

ORACLE REGULAR EXPRESSION TO FIND STRING BETWEEN TWO STRINGS

Introduction: 

Below is the syntax for regular expression REGEXP_SUBSTR

REGEXP_SUBSTR( string, pattern [, start_position [, nth_appearance [, match_parameter [, sub_expression ] ] ] ] )


Example:

The below expression can be used to obtain string between two string values using regular expression.

Lets suppose we have a string 'Hello world This is [Dinesh] - You are welcome to My Blog - Thanks for your support'.

I want to get string between string ('] -') and ('-') then use the below code

Query:

SELECT 
TRIM (REGEXP_SUBSTR ( 'Hello world This is [Dinesh] - You are welcome to My Blog. - Thanks for your support'  , ' \] - (.*?) \ - ',1,1,null,1))
FROM  DUAL;

Output:

You are welcome to My Blog.

Replace the strings ('] -') and ('-') with our own string in the expression.



        *?     Matches the preceding pattern zero or more occurrences.
        ( )     Used to group expressions as a sub expression.
         .      Matches any character except NULL. 


Instead of above format we can also use the below code

(REGEXP_SUBSTR('Hello world This is [Dinesh] - You are welcome to My Blog. - Thanks for your support' ,'\ - (.*?)\ - ',1,2,null,1))

This expression searches for the second pattern of the string '\ - (.*?)\ - ' .
Here (.*?)  acts like escape sequence.

No comments: