learn java
The moose likes Java in General and the fly likes replaceAll Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "replaceAll" Watch "replaceAll" New topic
Author

replaceAll

meghana maganti
Greenhorn

Joined: Sep 13, 2005
Posts: 11
I am trying to replace '*' with '%' in String


String value="*"
String str = value.replaceAll("*","%")
But I get a metadata error
David Patterson
Ranch Hand

Joined: Jul 01, 2002
Posts: 65
The first parameter for replaceAll is a String, but not a literal string, it is a regular expression.

The problem is that "*" has special meaning as part of an expression. To use a regular expression to match a single asterisk, use "\\*". The regular expression you want is '\*'. To get that you have to double the first backslash since "\*" is invalid -- it is not a valid Java escape sequence like "\n" or "\t". But "\\" means put in a single backslash. So if you code

String str = value.replaceAll("\\*","%");

it should work fine.

Dave Patterson
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Also, you can find more information on using regular expressions in Java here. If you don't know how to use regular expressions in general you should Google it.
 
Have you tried LearnNowOnline? http://www.learnnowonline.com/
 
subject: replaceAll