java - Regular expression to extract SQL query -
is there regex extracts sql queries string? i'm not interested validate sql syntax, rather , extracting selection of sql commands. parse given sql file/string in flexible manner.
given following sql file/string example:
select * test_table test_row = 'testing ; semicolon'; select * another_test_table; insert table_name values (value1,'value contains semicolon ;;;;',value3,...);
some pseudocode example be: ^(update|select|insert into)(.*)(;)$
. in future i'm looking extend (possible) commands.
- look starting match either: (update|select|insert|into)
- zero or more
any character
(including whitespaces , newlines) - stop @
;
, delimits sql query.
whenever possible via regex following java code able extract sql commands:
final string regex = "looking_for_this_one"; final pattern p = pattern.compile(regex, pattern.multiline); final matcher matcher = p.matcher(content); while (matcher.find()) { // matcher.group() contains full sql command }
thanks in advance!
i'll start off saying not way of doing it, , urge find method of doing it, preferrably tagging statements made, don't end in situation.
that being said, sql requires start 1 of following; delete
, select
, with
, update
or insert into
. requires input ends ;
.
we can use grab sequences matching sql following:
final string regex = "^(insert into|update|select|with|delete)(?:[^;']|(?:'[^']+'))+;\\s*$"; final pattern p = pattern.compile(regex, pattern.multiline | pattern.dotall);
group 1 holds operating word, in case wish filter valid sql on update
or select
.
see regex in action, cave-at here:
Comments
Post a Comment