2010-06-15 16 views

Odpowiedz

4

Dobrze kod źródłowy Pattern.quote jest dostępny i wygląda następująco:

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

zasadzie opiera się ona na

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

i ma specjalny treatement przypadku, w którym \E występuje w strunowy.

+0

To rzeczywiście dla mnie zrobić. Przepraszam za moją nowość, ale skąd zdobyłeś źródło? – AHungerArtist

+1

Źródło jest dostarczane wraz z SDK, w Eclipse możesz przesunąć -kliknąć na klasę, aby spojrzeć na jej źródło. –

+0

Dostępne do pobrania na stronie http://java.sun.com/javase/downloads/index.jsp – aioobe

2

Jest to kod z cytatem:

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

nie wydaje się trudne kopiowanie lub wykonawczych przez siebie lub?

Edit: aiobee był szybszy, sry

+1

Możesz dodać wartość do swojej odpowiedzi, zamieniając StringBuilder na StringBuffer; StringBuilder został wprowadzony dopiero w wersji JDK 1.5. –

1

Oto implementacja GNU Classpath (w przypadku obawy o pozwolenie Java ty):

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(); 
    } 
Powiązane problemy