We start out with some innocent code that will replace a variable with a certain value:
public static void main(String[] args) {
String quote = "$villain$ has an eye.";
String villain = "Sauron";
System.out.println(quote.replace("$villain$", villain));
}
We get this output:
Sauron has an eye.
All is well until we remember that there was also someone called Saurons' Mouth, so we change our quote to:
String quote = "$villain$ has an eye and $villain$ has a mouth.";
And since we now have multiple occurences of $villain$ we'll also use replaceAll instead of replace, right? Like this:
public static void main(String[] args) {
String quote = "$villain$ has an eye and $villain$ has a mouth.";
String villain = "Sauron";
System.out.println(quote.replaceAll("$villain$", villain));
}
Surprisingly, we get this output:
$villain$ has an eye and $villain$ has a mouth.
- This is a case of bad API design in Javas' String class.
- Always check, if parameters to String methods are plain strings or interpreted as regular expressions.
- There is also a possible performance penalty when using regular expressions
No comments:
Post a Comment