Reputation: 1179
replaceAll
with a value that contains '*' is throwing an exception.
I tried this
String tmp = "M ******* k";
tmp = tmp.replaceAll("****","NOT");
System.out.println("TMP is :"+tmp);
and I am getting this exception
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
Why does replaceAll
with *
have this behavior and how do I overcome with this problem?
Upvotes: 0
Views: 5825
Reputation: 122008
The first argument in replaceAll() takes a regular expression. The character '*' has a special meaning in regular expressions.
Replaces each substring of this string that matches the given regular expression with the given replacement.
So you have to escape it, if you want to match the literal character '*'.
Use "\\*".
Upvotes: 12
Reputation: 1193
You can check this code for reference:
public static void main (String[] args)
{
String tmp = "M ******* k";
tmp = tmp.replaceAll("\\*","NOT");
System.out.println("TMP is :"+tmp);
}
'*' is regular expression special char in java.So you need to follow rules of regular expressions.
http://docs.oracle.com/javase/tutorial/essential/regex/quant.html
Upvotes: 4
Reputation: 6071
Have you tried escaping the asterisks? As the PatternSyntaxException
points out, *
is a special character which requires a character class before it.
More appropriate way to do it would be:
tmp = tmp.replaceAll("\\*\\*\\*\\*", "NOT");
Upvotes: 1
Reputation: 109577
tmp = tmp.replace("****","NOT"); // No regular expression
tmp = tmp.replaceAll("\\*\\*\\*\\*","NOT");
The second alternative is the regular expression one.
Upvotes: 1