什么是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