Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java 1.4.2 equivalent of Pattern.quote()

What would be a Java 1.4.2 equivalent of Pattern.quote?

I was using Pattern.quote() on a URI but now need to make it 1.4.2 compatible.

like image 497
AHungerArtist Avatar asked Jun 15 '10 19:06

AHungerArtist


3 Answers

Well the source code of Pattern.quote is available and looks like this:

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();
}

Basically it relies on

\Q  Nothing, but quotes all characters until \E
\E  Nothing, but ends quoting started by \Q

and has a special treatement of the case in which \E is present in the string.

like image 200
aioobe Avatar answered Sep 23 '22 14:09

aioobe


This is the code of quote:

    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();
    }

Seems not hard copying or implementing by your self or?

Edit: aiobee was faster, sry

like image 22
Tobias P. Avatar answered Sep 25 '22 14:09

Tobias P.


Here's the GNU Classpath implementation (in case the Java license worries you):

  public static String quote(String str)
  {
    int eInd = str.indexOf("\\E");
    if (eInd < 0)
      {
        // No need to handle backslashes.
        return "\\Q" + str + "\\E";
      }

    StringBuilder sb = new StringBuilder(str.length() + 16);
    sb.append("\\Q"); // start quote

    int pos = 0;
    do
      {
        // A backslash is quoted by another backslash;
        // 'E' is not needed to be quoted.
        sb.append(str.substring(pos, eInd))
          .append("\\E" + "\\\\" + "E" + "\\Q");
        pos = eInd + 2;
      } while ((eInd = str.indexOf("\\E", pos)) >= 0);

    sb.append(str.substring(pos, str.length()))
      .append("\\E"); // end quote
    return sb.toString();
  }
like image 35
David Ehrmann Avatar answered Sep 24 '22 14:09

David Ehrmann