什么是Java 1.4.2等效的Pattern.quote()

时间:2010-06-15 19:47:09

标签: java regex java1.4

什么是Java 1.4.2等效的Pattern.quote?

我在URI上使用Pattern.quote()但现在需要使它与1.4.2兼容。

3 个答案:

答案 0 :(得分:4)

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的情况进行了特殊处理。

答案 1 :(得分:2)

这是引用代码:

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

似乎不是很难自己复制或实施?或

编辑:aiobee更快,sry

答案 2 :(得分:1)

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