¿Cuál sería el equivalente de Java 1.4.2 de Pattern.quote?¿Cuál es el equivalente de Java 1.4.2 de Pattern.quote()
Estaba usando Pattern.quote() en un URI pero ahora necesito hacerlo compatible con 1.4.2.
¿Cuál sería el equivalente de Java 1.4.2 de Pattern.quote?¿Cuál es el equivalente de Java 1.4.2 de Pattern.quote()
Estaba usando Pattern.quote() en un URI pero ahora necesito hacerlo compatible con 1.4.2.
bien el código fuente de Pattern.quote
está disponible y tiene el siguiente aspecto:
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();
}
Básicamente se basa en
\Q Nothing, but quotes all characters until \E
\E Nothing, but ends quoting started by \Q
y tiene con un tratamiento especial del caso en el que \E
está presente en el cuerda.
Este es el código de la cita:
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();
}
parece no copia dura o implementar por su cuenta propia o?
Editar: aiobee era más rápido, sry
Puedes agregar valor a tu respuesta reemplazando el StringBuilder con un StringBuffer; StringBuilder no se introdujo hasta JDK 1.5. –
Aquí está la implementación GNU de rutas de clases (en el caso de las licencias preocupaciones 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();
}
que va a hacer realidad para mí. Disculpe mi newbness, pero ¿cómo obtuvo la fuente? – AHungerArtist
La fuente está provista con el SDK, en eclipse puede desplazar-klick en una clase para ver su origen. –
Disponible para descargar en http://java.sun.com/javase/downloads/index.jsp – aioobe