Question

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?

Was it helpful?

Solution

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 "\\*".

oracle forum on the same

OTHER TIPS

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

Try

tmp = tmp.replaceAll("\\*+","NOT");

More;

Try escaping the *s:

tmp = tmp.replaceAll("\\*\\*\\*\\*","NOT");
tmp = tmp.replace("****","NOT"); // No regular expression
tmp = tmp.replaceAll("\\*\\*\\*\\*","NOT");

The second alternative is the regular expression one.

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top