android, matcher.appendReplacement(sb, '$8' ) 通过 ArrayIndexOutOfBoundsException

标签 android regex

它在 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)

“$”后跟数字有什么特别之处吗?

谢谢!

编辑:http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#appendReplacement%28java.lang.StringBuffer,%20java.lang.String%29解释一下!

最佳答案

来自 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/

相关文章:

java - 从 Android 中的 AlertDialog 选择/拍照

javascript - 如何使用 javascript/jquery 从字符串中删除文本?

android - PhoneGap/Cordova Android 开发

javascript - 如何用 javascript 中的空格替换换行符/换行符?

php - 如何查找子字符串并删除周围的P标签

javascript - 用于删除数字的正则表达式

arrays - 从数组中删除空白正则表达式命中

java - native 应用程序获取电池电量

android - 如何以编程方式设置 listView 的 state_pressed 颜色

java - Android:传递 Activity 类时为 "Expression expected"