Che cosa sarebbe un equivalente Java 1.4.2 di Pattern.quote?Qual è l'equivalente di Java 1.4.2 di Pattern.quote()
Stavo usando Pattern.quote() su un URI ma ora devo renderlo compatibile con 1.4.2.
Che cosa sarebbe un equivalente Java 1.4.2 di Pattern.quote?Qual è l'equivalente di Java 1.4.2 di Pattern.quote()
Stavo usando Pattern.quote() su un URI ma ora devo renderlo compatibile con 1.4.2.
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.
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
Puoi aggiungere valore alla tua risposta sostituendo StringBuilder con StringBuffer; StringBuilder non è stato introdotto fino a JDK 1.5. –
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();
}
che effettivamente fare per me. Scusa la mia newness, ma come hai ottenuto la fonte? – AHungerArtist
La sorgente viene fornita con l'SDK, in eclissi è possibile spostarsi su una classe per guardare la fonte. –
Disponibile per il download all'indirizzo http://java.sun.com/javase/downloads/index.jsp – aioobe