gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 08:54:02 26 4
gpt4 key购买 nike

这是在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com