We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpOther Libraries › String.replaceAll() not replacing parentheses
Page Index Toggle Pages: 1
String.replaceAll() not replacing parentheses (Read 3111 times)
String.replaceAll() not replacing parentheses
Aug 2nd, 2007, 5:46am
 
The following outputs "whee!(whee!)whee!". This is obviously because replaceAll takes a regex, not a straight string. Read on for my issue.

Code:
String s;

void setup(){
s = "()";
s = s.replaceAll("()","whee!");
println(s);
}


However, when I replace "\(\)", I get the error "Unexpected char '('." However, I thought \ would work as an escape character, and the Java docs say it does. What am I missing here?
Re: String.replaceAll() not replacing parentheses
Reply #1 - Aug 2nd, 2007, 7:20am
 
reading on in the docs you will find:

Quote:
Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.


hence:

Code:

String s;

void setup(){
s = "(replace me)";
s = s.replaceAll("\\(.+\\)","{with this}");
println(s);
}


F
Page Index Toggle Pages: 1