It's not a secret anymore!
The moose likes Beginning Java and the fly likes replaceAll( Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "replaceAll("+"," ")" Watch "replaceAll("+"," ")" New topic

replaceAll("+"," ")

Patrick Muls

Joined: Aug 08, 2001
Posts: 25
I'm trying to write a routine to concert attachements send from a HTML-form. One of the changes that need to be done is replacing all '+' by spaces. I tried using string.replace("+"," "), but got:
java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
Escaping \+ doenot work either.
Has anybody done this before?
Doug Wang
Ranch Hand

Joined: Oct 05, 2001
Posts: 445
I guess you used the new replaceAll method, whose signature is:
public String replaceAll(String regex, String replacement)
It throws PatternSyntaxException if the regular expression's syntax is invalid.
Or you may use the old replace(char oldc, char newc) method.
[ March 29, 2002: Message edited by: Doug Wang ]

Creativity is allowing yourself to make mistakes. Art is knowing which ones to keep
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
Did you try string.replace("\+"," ") or string.replace("\\+"," ")? The second one is the correct one I believe.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
This works just fine for me (using JDK 1.3):
String string = "+h+e+l+l+o+";

string = string.replace('+', ' ');

System.out.println(string); // prints " h e l l o "
I don't know if this relates to your problem:
It's important to note that the replace(char, char) returns a new String object (Strings are immutable), and so a reference must be made to that new String object in order to use it - the original String object is not changed.
Also, '\+' is an illegal escape character - as your compiler would let you know.
Good Luck.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: replaceAll("+"," ")
It's not a secret anymore!