Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the GWT replacement for java.util.regex.Pattern.quote(String arg)

Tags:

java

regex

gwt

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?

like image 400
A cup of tea Avatar asked Oct 21 '22 08:10

A cup of tea


1 Answers

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+)

like image 101
MartinTeeVarga Avatar answered Oct 28 '22 21:10

MartinTeeVarga