它在 Adroid 4.2.2 上运行。将正则表达式模式和匹配器与appendReplacement()一起使用。 它的作用是用一些自定义的数据替换从远程源接收的 html 字符串中的一些占位符。
奇怪的是,在“$8”之前,输入的所有其他字符串都很好。 '$'后跟任何数字都会抛出异常。仅使用数字或仅使用“$”不会抛出。 这是简化的代码 fragment 。
String patternStr = "(PlaceHolder)";
final Pattern cPattern = Pattern.compile(patternStr, Pattern.DOTALL);
StringBuffer sb = new StringBuffer();
Matcher matcher = cPattern.matcher(srcData);
try{
while(matcher.find()) {
String newData = "<span>Price: $8 </span> ";
try {
matcher.appendReplacement(sb, newData); //<== throws
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception(ex);
}
}
matcher.appendTail(sb);
异常显示:
java.lang.ArrayIndexOutOfBoundsException: length=4; index=16
java.util.regex.Matcher.group(Matcher.java:353)
java.util.regex.Matcher.appendEvaluated(Matcher.java:137)
java.util.regex.Matcher.appendReplacement(Matcher.java:110)
“$”后跟数字有什么特别之处吗?
谢谢!
最佳答案
来自 Matcher 的 oracle 页面:source
Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
尝试转义$
关于android, matcher.appendReplacement(sb, '$8' ) 通过 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532999/