Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

PatternSyntaxException w/ replaceAll

843785Dec 10 2008 — edited Dec 10 2008
String msg="what is up?";
String[] s = msg.split(" ");
String[] r = {"?","!",",",".","+"};
for(int i=0;i<s.length;i++){
     for(int j=0;j<r.length;j++){
          if(s.contains(r[j])){
s[i]=s[i].replaceAll(r[j], "");
}
}
}

Throws: Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0 @ the replaceAll

Some googling showed that adding "\\" in front of the ? should fix it. But this doesn't seem to work. (IE r = {"\\?","!",",",".","+"}; )
It doesn't see that "\\?" is contained.

So I removed the check for containing...
String msg="what is up?";
String[] s = msg.split(" ");
String[] r = {"\\?","!",",",".","\\+"};
for(int i=0;i<s.length;i++){
     for(int j=0;j<r.length;j++){
          s=s[i].replaceAll(r[j], "");
}
System.out.println(s[i]);
}


It prints out nothing.
So some how, s[i] is empty after it replaces everything. I don't understand what's happening.

How can i remove these characters from my String?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 7 2009
Added on Dec 10 2008
5 comments
168 views