Jaki byłby odpowiednik Pattern.quote w wersji 1.4.2 Java?Co to jest odpowiednik Java 1.2.2 Pattern.quote()
Użyłem Pattern.quote() na identyfikatorze URI, ale teraz muszę go dostosować do wersji 1.4.2.
Jaki byłby odpowiednik Pattern.quote w wersji 1.4.2 Java?Co to jest odpowiednik Java 1.2.2 Pattern.quote()
Użyłem Pattern.quote() na identyfikatorze URI, ale teraz muszę go dostosować do wersji 1.4.2.
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.
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
Możesz dodać wartość do swojej odpowiedzi, zamieniając StringBuilder na StringBuffer; StringBuilder został wprowadzony dopiero w wersji JDK 1.5. –
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();
}
To rzeczywiście dla mnie zrobić. Przepraszam za moją nowość, ale skąd zdobyłeś źródło? – AHungerArtist
Źródło jest dostarczane wraz z SDK, w Eclipse możesz przesunąć -kliknąć na klasę, aby spojrzeć na jej źródło. –
Dostępne do pobrania na stronie http://java.sun.com/javase/downloads/index.jsp – aioobe