wood burning stoves*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "$ in String.replaceAll() problem" Watch "$ in String.replaceAll() problem" New topic
Author

$ in String.replaceAll() problem

Bruce Jin
Ranch Hand

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


BJ - SCJP and SCWCD
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
author
Sheriff

Joined: Sep 28, 2004
Posts: 18509
    
  40

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



Henry


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

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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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: 666
Thanks Ernest.
Now I got it!
We are encoding \ with \\ and $ with \$.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: $ in String.replaceAll() problem
 
Similar Threads
regex replacement
questions regarding regular expressions
String.replaceAll
Help replacing characters using XSL
mysql & incomplete insertions!