Что такое Java 1.4.2 эквивалентный Pattern.quote () - PullRequest
7 голосов
/ 15 июня 2010

Что было бы эквивалентным Pattern.quote в Java 1.4.2?

Я использовал Pattern.quote () для URI, но теперь необходимо сделать его совместимым с 1.4.2.

Ответы [ 3 ]

4 голосов
/ 15 июня 2010

Хорошо, исходный код Pattern.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();
}

В основном это зависит от

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

и имеет специальную обработку случая, в котором \E присутствует в строке.

2 голосов
/ 15 июня 2010

Это код цитаты:

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

Кажется, вы не копируете и не печатаете сами, или?

Редактировать: Айоби был быстрее, sry

1 голос
/ 04 ноября 2013

Вот реализация GNU Classpath (на случай, если лицензия Java вас беспокоит):

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