什麼是Pattern.quote的Java 1.4.2等效項?什麼是Pattern.quote()的Java 1.4.2等效項
我在URI上使用Pattern.quote(),但現在需要使它與1.4.2兼容。
什麼是Pattern.quote的Java 1.4.2等效項?什麼是Pattern.quote()的Java 1.4.2等效項
我在URI上使用Pattern.quote(),但現在需要使它與1.4.2兼容。
井Pattern.quote
的源代碼是可用的,看起來像這樣:
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();
}
基本上它依賴於
\Q Nothing, but quotes all characters until \E
\E Nothing, but ends quoting started by \Q
,並具有殼體的特殊treatement其中\E
存在於串。
這是引用的代碼:
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();
}
好像並不難複製或通過你自己或實施?
編輯:aiobee增快,SRY
你可以通過用StringBuffer替換StringBuilder來爲你的回覆添加值;直到JDK 1.5才引入StringBuilder。 – 2010-06-15 21:15:10
這裏的GNU Classpath的執行(如果在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();
}
這實際上會爲我做。請原諒我的新鮮事,但你是如何獲得信息來源的? – AHungerArtist 2010-06-15 19:52:09
源代碼隨SDK一起提供,在eclipse中你可以移動 - 輕敲一個類來查看它的源代碼。 – 2010-06-15 19:53:07
可在http://java.sun.com/javase/downloads/index.jsp上下載 – aioobe 2010-06-15 19:54:04