Java_Alert
Java_Alert

Reputation: 1179

replaceAll with '*'

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

Answers (6)

Suresh Atta
Suresh Atta

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

oracle forum on the same

Upvotes: 12

Manish Doshi
Manish Doshi

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

karllindmark
karllindmark

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

Joop Eggen
Joop Eggen

Reputation: 109577

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

The second alternative is the regular expression one.

Upvotes: 1

hd1
hd1

Reputation: 34677

Try escaping the *s:

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

Upvotes: 1

Prasanth
Prasanth

Reputation: 5258

Try

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

More;

Upvotes: 1

Related Questions