I need to use a regular expression to find and replace double-quotes (") in an SQL string, but I need to limit the replacement to only one part of the string. I need this for an Ant task I'm working on (hey, ant is Java), but if the only good solution I can find is straight up Java, that is fine also. For example, if I have the String:
Some "arbitrary text" says INSERT INTO foo VALUES( "bar1", "bar2", "bar3");
I only want to replace the double quotes (") inside the VALUES clause, not the "arbitrary text" part. Is there a way to anchor the parttern matching so that it only matches and replaces inside of the VALUES clause?
Well, there may be ways to do this in a single regex using lookbehind, but I think that would be needlessly confusing and buggy. I would recommend splitting the process into several parts: use one regex to identify the beginning and end of the VALUES clause, then use substring() to isolate that section and do replacement on it. Then put the pieces back together with a StringBuilder, or maybe just concatenate with +.
The more difficult parts here depend on just what can occur in that "arbitrary text", and in the double-quoted sections. Is it possible that either of these might contain the word "values", separate from the true values() clause? What about ( or )? Is there any way to escape a ", e.g. as "" or \"? Can there be arbitrary text after the values() clause? All of these can complicate the solution...
"I'm not back." - Bill Harding, Twister
subject: Anchoring a Regular Expression to only "part" of a String