What would be a Java 1.4.2 equivalent of Pattern.quote?
I was using Pattern.quote() on a URI but now need to make it 1.4.2 compatible.
Well the source code of Pattern.quote
is available and looks like this:
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();
}
Basically it relies on
\Q Nothing, but quotes all characters until \E
\E Nothing, but ends quoting started by \Q
and has a special treatement of the case in which \E
is present in the string.
This is the code of 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();
}
Seems not hard copying or implementing by your self or?
Edit: aiobee was faster, sry
Here's the GNU Classpath implementation (in case the Java license worries you):
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With