This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
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: 671
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: 20370

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: 671
Thanks Henry,
I was trying \$ not \\$.
Why use \\ to encode $?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195

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: 671
Thanks Ernest.
Now I got it!
We are encoding \ with \\ and $ with \$.
wood burning stoves
subject: $ in String.replaceAll() problem
It's not a secret anymore!