I had a requirement where i need to insert an escape sequence in a given string variable, at places wherever a single quotes (\') appears. I tried using
String in = ...
StringBuilder out = new StringBuilder(in.length() + 16);
for (int i=0; i<in.length(); i++) {
char c = in.charAt(i);
if (c == '\'') {
out.append("\\'");
} else {
out.append(c);
}
}
String result = out.toString();
message = message.replaceAll("'", "");
how about this:
newMessage.replace("'", "\\'")
Or do I misunderstand your requirement?
And about the discussions in comments: yes, both replace()
and replaceAll()
use Regular Expressions use compiled Patterns internally (but replace()
uses the flag Pattern.LITERAL), interpreting the pattern as literal value, whereas replaceAll()
(and replaceFirst()
) both use Regular Expressions. However, the compiled patterns are absolutely identical (in this case). Try it yourself:
Pattern literal = Pattern.compile("'",Pattern.LITERAL);
Pattern regular = Pattern.compile("'");
Add a breakpoint after these assignments and take a closer look at these two compiled patterns. You will find that all of their field values are identical, so in this case at least, no it doesn't make any difference performance-wise.
I would use a StringBuilder object rather than manually concatinating the strings. At least you would get some performance improvement out of that if your strings are large.
Use the replaceAll
method:
myString.replaceAll("'", "\\'");