java - Java REGEX appendReplacement() 方法不接受第二个参数中的变量
问题描述
我有来自文件的以下字符串:
{"comment":"<p>Some text with double quotes like (example, "$", "(", ")", etc.) here in a paragraph.</p>","replies":{"1":{"user":"Some User1","reply":"<p>This is another sample "data" with some double quotes.</p>","lastModified":"2017-04-12T15:03:06Z"},"2":{"user":"SomeUser2","reply":"<p>Yet another "data" with some more double quotes.</p>","lastModified":"2017-04-12T15:03:06Z"}}}
我的目标是转义 HTML p(段落)标签中的双引号字符,我尝试这样做的方式是:
public class Test {
public static void main(String[] args) {
FileInputStream fis;
try {
fis = new FileInputStream("PATH_TO_FILE");
String data = IOUtils.toString(fis, "UTF-8");
System.out.println("ORIGINAL: " + data + "-");
Pattern pTagPattern = Pattern.compile("(<p>)(.*?)(</p>)");
Matcher pTagMatcher = pTagPattern.matcher(data);
String str ;
Map<Integer, String> map = new HashMap<Integer, String>();
int i = 1;
while(pTagMatcher.find()) {
map.put(i++, StringEscapeUtils.escapeJava(pTagMatcher.group(2)));
}
Matcher pTagMatcher1 = pTagPattern.matcher(data);
StringBuffer sb1 = new StringBuffer();
int j = 1;
String str1;
while(pTagMatcher1.find()) {
str1 = map.get(j);
pTagMatcher1.appendReplacement(sb1, str1); //<=== EXCEPTION HERE
j++;
}
pTagMatcher1.appendTail(sb1);
System.out.println("\nFINAL Text is: " + sb1.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当我运行上面的代码时,我得到如下异常:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
at java.util.regex.Matcher.appendReplacement(Unknown Source)
at my.project.package.util.Test.main(Test.java:54) (The line in the code above where I have "<=== EXCEPTION HERE")
异常在线:
pTagMatcher1.appendReplacement(sb1, str1);
在这里,对于appendReplacement()
方法的第二个参数,我尝试使用变量而不是实际的文字字符串。当我使用像“示例文本”这样的文字字符串时,它可以工作。
我对 Java 正则表达式不是很熟悉,因此如果有人能指出我在这里做错了什么,我将不胜感激。或者,如果有人可以提出另一种更好的方法来做到这一点,那就太好了。
谢谢。
解决方案
推荐阅读
- reactjs - 大型模块项目的 Webpack - 减少构建时间
- angular - 如何在渲染前获取 Http 请求响应 - Angular Universal
- flutter - Flutter:statefull 组件未在 statefull 屏幕/页面内更新
- php - 为什么 post_class() 函数将 css 类应用于 Wordpress 中的所有其他文件?
- html - 如何使用纯 CSS 的复选框更改正文的背景颜色(如果可能的话)
- c++ - 带有 const onject 的 std::vector 不可访问性
- javascript - Flask onchange 事件还是需要 Javascript 框架?
- python - 为什么蛇坐标不改变方向到另一边
- python - Python Debian Docker 映像无法再更新
- python - 关于装饰器函数的一些事情