File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Anchoring a Regular Expression to only Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Anchoring a Regular Expression to only "part" of a String" Watch "Anchoring a Regular Expression to only "part" of a String" New topic

Anchoring a Regular Expression to only "part" of a String

The Dunce Baron

Joined: Apr 19, 2007
Posts: 9
Hello Group,

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?

Thanks for any advice.

Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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
I agree. Here's the link:
subject: Anchoring a Regular Expression to only "part" of a String
It's not a secret anymore!