public CharSequence replace(CharSequence input, CharSequence replacement) throws XPathException {
// preprocess the replacement string: .NET uses $$ to represent $, and doesn't treat \ specially
// The calling code will already have validated the replacement string, so we can assume for example
// that "\" will be followed by "\" or "$".
FastStringBuffer sb = new FastStringBuffer(replacement.length() + 4);
for (int i=0; i<replacement.length(); i++) {
final char ch = replacement.charAt(i);
if (ch == '\\') {
if (replacement.charAt(i+1) == '\\') {
sb.append('\\');
} else if (replacement.charAt(i+1) == '$') {
sb.append("$$");
} else {
throw new IllegalArgumentException("bad replacement string");
}
i++;
} else if (ch == '$') {
int n = 0;
while (true) {
if (i+1 >= replacement.length()) {
break;
}
char d = replacement.charAt(i+1);
int dval = "0123456789".indexOf(d);
if (dval < 0) {
break;
}
i++;
n = n*10 + dval;
}
processGroupReference(n, sb);
} else {
sb.append(ch);
}
}
//System.err.println("original replacement string: " + replacement);
//System.err.println("processed replacement string: " + sb);
return pattern.Replace(input.toString(), sb.toString());
}