如何使用正则去掉html中标签与标签之间的空格

使用正则表达式替换匹配两个标签之间空格的字符串来去掉 HTML 中标签与标签之间的空格。步骤包括:定义正则表达式匹配 HTML 标签和标签之间的空格。使用正则表达式替换,用匹配的字符串替换捕获组(标签和标签之间的空格)。

如何使用正则去掉html中标签与标签之间的空格

如何使用正则表达式去掉 HTML 中标签与标签之间的空格

方法:

使用正则表达式替换匹配两个标签之间空格的字符串。

步骤:

  1. 定义正则表达式:

    (<[^>]+>)s+(<[^>]+>)
  • ]+> 匹配任意 HTML 标签。
  • s+ 匹配一个或多个空格字符。
  1. 使用正则表达式替换:

    String html = "<h1>标题</h1><p>内容</p>
                        <div class="aritcle_card">
                            <a class="aritcle_card_img" href="/ai/1301">
                                <img src="https://img.php.cn/upload/ai_manual/001/431/639/68b6d8ba9040c297.png" alt="AI Content Detector">
                            </a>
                            <div class="aritcle_card_info">
                                <a href="/ai/1301">AI Content Detector</a>
                                <p>Writer推出的AI内容检测工具</p>
                                <div class="">
                                    <img src="/static/images/card_xiazai.png" alt="AI Content Detector">
                                    <span>119</span>
                                </div>
                            </div>
                            <a href="/ai/1301" class="aritcle_card_btn">
                                <span>查看详情</span>
                                <img src="/static/images/cardxiayige-3.png" alt="AI Content Detector">
                            </a>
                        </div>
                    ";
    String noSpaceHtml = html.replaceAll("(<[^>]+>)\s+(<[^>]+>)", "$1$2");
  • replaceAll() 方法用正则表达式匹配的字符串替换原字符串。
  • $1$2 是捕获组,分别表示标签和标签之间的空格。

示例:

输入 HTML:

<h1>标题<h1><p>内容</p>

输出 HTML(已删除空格):

<h1>标题</h1><p>内容</p>

以上就是如何使用正则去掉html中标签与标签之间的空格的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。