You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将正则匹配的独立HTML标签替换为XHTML闭合语法?

正则匹配独立标签并批量替换的实现

问题背景

现有正则表达式:

/<(\w+)>(?!\w)(?!(</(\1)>))/gm

示例文本:

RegExr was created by gskinner.com.

Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & JavaScript flavors of RegEx are supported. Validate your expression with Tests mode.

The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community and view patterns you create or favorite in My Patterns.
amir
Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English.
<p>sdf,m.,.msdf</p><p><p><p><p></p>
<b></b>
<p><b><g>
<img>
<br><p><hr>
<p>

该正则可匹配类似末尾<p>这样的独立未闭合标签,需要将每个匹配到的标签(如<p>)转换为</p>,即在标签的最后一个字符前插入/,但不清楚如何对每个匹配项单独执行替换操作。

解决方案

利用正则的捕获组功能,直接在替换规则中引用捕获到的标签名即可完成批量替换:

替换规则

使用</$1>作为替换字符串(其中$1对应正则中第一个捕获组匹配到的标签名称)。

具体实现(以JavaScript为例)

const text = `RegExr was created by gskinner.com.

Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & JavaScript flavors of RegEx are supported. Validate your expression with Tests mode.

The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community and view patterns you create or favorite in My Patterns.
amir
Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English.
<p>sdf,m.,.msdf</p><p><p><p><p></p>
<b></b>
<p><b><g>
<img>
<br><p><hr>
<p>`;

const regex = /<(\w+)>(?!\w)(?!(<\/(\1)>))/gm;
const result = text.replace(regex, '</$1>');
console.log(result);

效果说明

执行替换后,所有匹配到的独立标签都会被转换为对应的闭合标签:

  • 原末尾的<p>会变成</p>
  • 孤立的<g>会变成</g>
  • 孤立的<img>会变成</img>

如果你的需求是将标签改为自闭合形式(如<p>→<p/>),只需将替换字符串改为<$1/>即可。

内容的提问来源于stack exchange,提问作者user10997800

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:23:17