This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "replaceAll" Watch "replaceAll" New topic


meghana maganti

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.
jQuery in Action, 2nd edition
subject: replaceAll
Similar Threads
Looking for correct data type to take in stream of xml
Please Comment on Data Section
how to sovle these two errors~~~help~~~
SQL Data Types
amount currency datatype