In my app I need the code like:
string1.replaceAll(string2, myConstatntString)
Problem is that string1
and string2
can contain special symbols like '('
.
I wish to quote string2
using java.util.regex.Pattern.quote(String arg)
:
string1.replaceAll(Pattern.quote(string2), myConstatntString);
But java.util.regex.Pattern
is not available in GWT client side. Does GWT have any replacements for Pattern.quote
?
I believe there isn't, because JavaScript doesn't have its own method. What you can do is to use String.replace()
instead of String.replaceAll()
, given that you don't need regexp at all. If you do, you will have to write your own method.
This is how it is done in JavaScript: Is there a RegExp.escape function in Javascript?
And this is how it is done in Java:
public static String quote(String s) {
int slashEIndex = s.indexOf("\\E");
if (slashEIndex == -1)
return "\\Q" + s + "\\E";
StringBuilder sb = new StringBuilder(s.length() * 2);
sb.append("\\Q");
slashEIndex = 0;
int current = 0;
while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
sb.append(s.substring(current, slashEIndex));
current = slashEIndex + 2;
sb.append("\\E\\\\E\\Q");
}
sb.append(s.substring(current, s.length()));
sb.append("\\E");
return sb.toString();
}
From: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/regex/Pattern.java
(the actual implementation in Java 1.5+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With