我是正则表达式世界的新手。任何有关以下主题的帮助将不胜感激。
我有一个包含 xml 内容的 java 字符串。我想替换两种类型的父标签之间出现的所有图像标签。 (<Comment> and <Link>
)
示例:
字符串输入 = "<Comment> 1 2<img>This should be removed</img> 4 </Comment><Link>5 <img>This should be removed</img> 6</Link> <Comment> 7 <img>This should be removed</img> 8 </Comment>";
所需输出 = "<Comment> 1 2 4 </Comment><Link>5 6</Link> <Comment> 7 8 </Comment>"
;
我有下面的工作代码,它完美地替换了所有 <Comment>
中出现的所有图像标签。标签。我对这两个标签一起检查感到震惊,即 <Comment> and <Link>
。请忽略 while 循环中替换标签的逻辑,因为我还没有更新它。我对第一行感到震惊,即传递多个模式并识别组。
Pattern pattern = Pattern.compile("<comments>(.*?)</comments>");
Matcher matcher = pattern.matcher(input );
while (matcher.find()) {
String comment = matcher.group(1);
String replace = "<comments>" + comment + "</comments>";
Document document = Jsoup.parse(replace, "", Parser.xmlParser());
String cleanPdfXml = Jsoup.clean(document.select("comments").text(), Whitelist.relaxed());
String replacedTo = StringEscapeUtils.escapeXml(cleanPdfXml.replace("\n", ""));
replacedTo = "<comments>" + replacedTo + "</comments>";
input = input .replace(replace, replacedTo);
}
最佳答案
您可以使用以下方法:
String inputString = "<Comment> 1 2<img>This should be removed</img> 4 </Comment><Link>5 <img>This should be removed</img> " +
"6</Link> <Comment> 7 <img>This should be removed</img> 8 </Comment>";
String outputString = inputString.replaceAll("(?s)<img>.*?</img>", "");
System.out.println( outputString);
关于java - 多个正则表达式模式来替换多次出现的图像标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60023993/