I have a multiple line string like following:
END IF; EXECUTE IMMEDIATE ' CREATE INDEX #idx1 ON somename ( row_id, something)'; IF v_sys_error 0 THEN GOTO SQL_ERROR; END IF;
I wish to capture the part in bold (meaning everything from EXECUTE IMMEDIATE to next semicolon.
I have the following regex but how can I change it to work with multiple lines?
(EXECUTE).*;
Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.
The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.
Line breaks If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”.
The fundamental building blocks of a regex are patterns that match a single character. Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" .
(?m) makes the regex multiline - allows you to match beginning (^) and end ($) of string operators (in this case, to match the beginnings and ends of individual lines, rather than the whole string):
/(?m)(EXECUTE).*?;/
(?s) - dotall flag - makes the regex match newlines with . (dot) operators:
/(?s)(EXECUTE).*?;/
The following should work in Groovy.
def s = """ END IF; EXECUTE IMMEDIATE ' CREATE INDEX #idx1 ON somename ( row_id, something)'; IF v_sys_error <> 0 THEN GOTO SQL_ERROR; END IF; """ def expect = """ EXECUTE IMMEDIATE ' CREATE INDEX #idx1 ON somename ( row_id, something)'; """.trim() def exe = s =~ /(?ms)(EXECUTE.*?;)/ assert expect == exe[0][1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With