I will begin by saying that this is not a good way to do this, and urge you to find another way to do this, preferably marking it right where statements are made so that you do not end up in this situation.
At the same time, SQL requires that it starts with one of the following: DELETE , SELECT , WITH , UPDATE or INSERT INTO . It also requires that the entry end with ; .
We can use this to capture all sequences matching SQL, as follows:
final String regex = "^(INSERT INTO|UPDATE|SELECT|WITH|DELETE)(?:[^;']|(?:'[^']+'))+;\\s*$"; final Pattern p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);
In group 1, the operational word is now executed if you want to filter valid SQL by UPDATE or SELECT .
See the regex in action, as well as the cave here:
https://regex101.com/r/dt9XTK/2
source share