File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login Today (12/10) is CodeRanch Day in Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal. CodeRanch Day is 50% off our pick of books: Secrets of the JavaScript Ninja; The Well-Grounded Java Developer; Java 8 Lambdas in Action; HTML5 in Action; The Responsive Web; and Java Persistence with Hibernate

# replacing string with '\' character

Edmund Castermund
Ranch Hand

Joined: May 09, 2007
Posts: 80
Hi,
I'm trying to do a string.replaceAll(MatcherGroupThatContainsFilePath, "new string");

I'm getting an error.

compling with 1.5

I'm reading a file, looking for a regex, then creating a new string that modifies the text the regex found, then trying to replace the old string with the new. It's the first argument in the text.replaceAll(old, new) that's the problem.
thanks,
jason
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
Could you post what MatcherGroupThatContainsFilePath is holding ?

JDBCSupport - An easy to use, light-weight JDBC framework -
Edmund Castermund
Ranch Hand

Joined: May 09, 2007
Posts: 80
Hi,
the string I'm trying to replace has a windows file path in it. Here's some code that recreates the problem:

this generates:

In perl there's a function: \Q$string\E you can use, where you're telling perl that you don't want anything inside$string to be evaluated as a regex. Is there anything similar in java?
What I'm trying to do is to in the actual situation (it's for work, so I don't want to post the actual data) is replace a <!DOCTYPE root-element c:\path\to\dtd> tag (that contains a file path) with a commented out doctype tag: <!-- <!DOCTYPE root-element c:\path\to\dtd> -->
jason

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 34576

13
Try using \\\\ instead of \\.

What happens is that the compiler sees \\ as an escape for \, so it looks for something after the \\ and finds \h which isn't appropriate. You want it to see \\ so you need to escape the first \ to \\ and you need to escape the second \ to \\.
Edmund Castermund
Ranch Hand

Joined: May 09, 2007
Posts: 80
Hi,
I tried that, and quite a few variations besides...but I still couldn't get it to work.
The code you mentioned just didn't do anything.

I found this code online somewhere that seemed to do the trick:

Edmund Castermund
Ranch Hand

Joined: May 09, 2007
Posts: 80

This gave me the desired result:

I think the reason it wasn't working for me before is that I didn't create a new variable...
thanks
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 34576

13
You're welcome

subject: replacing string with '\' character
[newbie] regex anomaly
writing into the previous line
Ant ReplaceRegExp
Are there any problems using the same statement for multiple queries?
Compiling blank lines patterns using regex