2010-06-15 103 views

回答

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 

,并具有壳体的特殊treatement其中\E存在于串。

+0

这实际上会为我做。请原谅我的新鲜事,但你是如何获得信息来源的? – AHungerArtist 2010-06-15 19:52:09

+1

源代码随SDK一起提供,在eclipse中你可以移动 - 轻敲一个类来查看它的源代码。 – 2010-06-15 19:53:07

+0

可在http://java.sun.com/javase/downloads/index.jsp上下载 – aioobe 2010-06-15 19:54:04

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

+1

你可以通过用StringBuffer替换StringBuilder来为你的回复添加值;直到JDK 1.5才引入StringBuilder。 – 2010-06-15 21:15:10

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(); 
    } 
相关问题