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 $ in String.replaceAll() problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "$ in String.replaceAll() problem" Watch "$ in String.replaceAll() problem" New topic

$ in String.replaceAll() problem

Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 672
This code does not work because of $ sign. How to make it work? Thanks.

We love Java programming. It is contagious, very cool, and lot of fun. - Peter Coad, Java Design

Crazy Bikes created by m-Power
Henry Wong

Joined: Sep 28, 2004
Posts: 20535

The "$" has special meaning in a replacement string. If you actually mean a "$" character, then you must escape the character...


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 672
Thanks Henry,
I was trying \$ not \\$.
Why use \\ to encode $?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Originally posted by Bruce Jin:

Why use \\ to encode $?

This comes up quite often in regular expression work. The "\" backslash is an escape character for both the Java compiler and the regular expression compiler. If you want to tell the regular expression compiler to ignore a characters special meaning, then the regular expression compiler must see a "\" before that character. But since "\" means something to the Java compiler too, if you put just one "\" into a String it disappears (or does the wrong thing.) You must put two backslashes into a String literal to get one actual backslash character into a String. Only then will the regular expression compiler see it.
[ November 06, 2006: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Bruce Jin
Ranch Hand

Joined: Sep 20, 2001
Posts: 672
Thanks Ernest.
Now I got it!
We are encoding \ with \\ and $ with \$.
I agree. Here's the link:
subject: $ in String.replaceAll() problem
It's not a secret anymore!