- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
这是在 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/
public class TestUtil { public static void main(String[] args) { StringBuffer test = new
public static void main(String[] args) { Pattern p = Pattern.compile("((?:[a-zA-Z]\\.)+[s]$)
正则表达式中的3组: 模式 = (a)(b)123(c) 我需要摆脱 a,b,c 在 Java 中: while (matcher.find()) { matcher.appendReplacem
我正在使用 Matcher.appendReplacement()在我的替换字符串中有 $2 之前,它工作得很好: Note that backslashes ( \ ) and dollar sig
我正在使用 jdk1.7.0_79 尝试用 Matcher 替换一些文本。我大量使用了 Matcher.appendReplacement() 和 Matcher.appendTail(),当我没有设
java Matcher.appendReplacement() 方法(带有 appendTail())应该可以让我将源文本转换为结果文本,同时替换所有出现的模式。伪语言中的算法类似于: while
我有一个字符串 s 和一个正则表达式。我想用替换字符串替换 s 中正则表达式的每个匹配项。替换字符串可能包含一个或多个反斜杠。为了执行替换,我使用了 Matcher 的 appendReplaceme
这是在 Adroid 4.2.2 上运行的。将正则表达式模式和匹配器与 appendReplacement() 结合使用。它所做的是用一些自定义数据替换从远程源接收的 html 字符串中的一些占位符。
是否有 Matcher.appendReplacement() 和 Matcher.appendTail() 的替代方案,它采用 StringBuilder 而不是 StringBuffer ? 是否
更新 这是我想出的。我还没有测试它,因为它是仍然需要移植的更大代码段的一部分。 你能看到任何看起来不合适的东西吗? private const string tempUserBlock = "%%%C
我是一名优秀的程序员,十分优秀!