多个正则表达式模式替换多次出现的图像标签

问题描述 投票:1回答:1

我是regex世界的新手。与以下主题有关的任何帮助将不胜感激。

我有一个包含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);

        }
java regex regex-lookarounds regex-negation regex-group
1个回答
0
投票

您可以使用以下方法:

Pattern pattern = Pattern.compile("<img[^>]*?>");
Matcher matcher = pattern.matcher(inputString);
matcher.replaceAll("");
© www.soinside.com 2019 - 2024. All rights reserved.