Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

replaceAll

 
meghana maganti
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to replace '*' with '%' in String


String value="*"
String str = value.replaceAll("*","%")
But I get a metadata error
 
David Patterson
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic