2010-06-15 7 views

risposta

4

Bene il codice sorgente di Pattern.quote è disponibile e si presenta così:

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

Fondamentalmente si basa su

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

e ha un trattamento speciale del caso in cui \E è presente nel stringa.

+0

che effettivamente fare per me. Scusa la mia newness, ma come hai ottenuto la fonte? – AHungerArtist

+1

La sorgente viene fornita con l'SDK, in eclissi è possibile spostarsi su una classe per guardare la fonte. –

+0

Disponibile per il download all'indirizzo http://java.sun.com/javase/downloads/index.jsp – aioobe

2

Questo è il codice di citazione:

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

sembra non copia duro o attuare dal vostro auto o?

Edit: aiobee era più veloce, SRY

+1

Puoi aggiungere valore alla tua risposta sostituendo StringBuilder con StringBuffer; StringBuilder non è stato introdotto fino a JDK 1.5. –

1

Ecco l'implementazione GNU Classpath (nel caso in cui le licenze preoccupazioni 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(); 
    } 
Problemi correlati