Reputation: 371
I need to cover off two scenarios within a string function.
I have a large string containing multiple SQL statements, which I need to split on ';' except in the above scenarios where there is a commented block, or the semi-colon exists in a function - ironically such as REGEXP()
I have tried to put a second negative lookahead block before or after the existing, but it never seems to work.
String[] queries = queryParam.trim().split(";(?![^()]*\\))");
-- Works for parenthesis
String[] queries = queryParam.trim().split(";(?![^()]*\\))(?!-*\-)");
-- Does not work
String[] queries = queryParam.trim().split(";(?!-*\-)(?![^()]*\\))");
-- Does not work
https://regex101.com/r/Sdx8TC/1
Upvotes: 1
Views: 125
Reputation: 1279
I came up with this regex:
((?:(?:\-\-[^*]*+(?:[^\-\-][^*]*\-\-)*|(?:[^\-\-]|\-\-\n?)*?\n)|(?:\((?:\(.|[^\(])*\(|\((?:\).|[^\)])*\)|.[^\)\;]*))*?)(;)
The regex ensures the following:
Link to see the regex in action: https://regex101.com/r/AFnWqD/1/
Upvotes: 1
Reputation: 163277
Your second requirement is if line starts with '--'
. In that case the negative lookahead (?!-*\-)
is not going to work because your match starts with ;
so that line can not start with --
anymore.
What you might do using your patterns is first check if the string starts with -- using for example matches in combination with this pattern:
^[ \\t]*--.*$
If that matches, then use split with your pattern:
;(?![^()]*\\))
For example:
String[] strings = {
" --hello;(hello;hello)hello;",
"hello;(hello;hello)hello;"
};
for (String s : strings) {
if (!s.matches("^[ \\t]*--.*$")) {
System.out.println(Arrays.toString(s.split(";(?![^()]*\\))")));
}
}
Result:
[hello, (hello;hello)hello]
Upvotes: 0