Saturday, June 11, 2011

Dangling meta character '?' near index 0

Problem

String str = "testing??"; 

str = str.replaceAll("?", ""); 
// Please note that the problem is only with replaceAll and not with replace.
str = str.replace("?", "");


When you use the above pattern you get an exception as "Dangling meta character '?' near index 0"


Solution
String str = "testing??"; 

str = str.replaceAll("\\?", ""); 

You can use the above solution when you are replacing * and + symbols
String str = "testing??*+"; 

str = str.replaceAll("\\*", ""); //"Dangling meta character '*' near index 0" 
str = str.replaceAll("\\+", ""); //"Dangling meta character '+' near index 0"

3 comments:

  1. String s = "28.02.2014";
    s = s.replaceAll(".", "/");

    The output will be every character will be replaced by a /

    In order to get correct results, you need to escape the .

    s = s.replaceAll("\\.","/");

    ReplyDelete