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

如何用正则表达式处理动态HTML内容:移除&emsp;并添加<ul>包裹?

解决方案

核心正则逻辑

针对你的需求,我们可以通过捕获组保留用户动态输入内容,同时完成标签调整和字符移除。以下是适配单条<li>场景的正则方案:

正则表达式(以JavaScript为例)

匹配模式:

(<p><code>&lt;li&gt;&amp;emsp;)(.*?)(&lt;/li&gt;</code>\.)<\/p>

替换模板:

<p><code>&lt;ul&gt;&lt;li&gt;$2&lt;/li&gt;&lt;/ul&gt;</code></p>

各部分解析

  • (<p><code>&lt;li&gt;&amp;emsp;):捕获固定前缀,包含外层<p><code>、转义后的<li>标签和需要移除的&emsp;
  • (.*?):非贪婪捕获组,匹配用户输入的任意动态内容(避免过度匹配多个<li>)
  • (&lt;/li&gt;</code>\.)<\/p>:捕获固定后缀,包含转义后的</li>、</code>、多余的句号和外层</p>
  • $2:引用捕获到的用户动态内容,确保替换后保留原始输入

示例代码

const originalStr = '<p>I have a string</p><p><code>&lt;li&gt;&amp;emsp;Content Test 1&lt;/li&gt;</code>.</p>';
const regex = /(<p><code>&lt;li&gt;&amp;emsp;)(.*?)(&lt;/li&gt;</code>\.)<\/p>/g;
const result = originalStr.replace(regex, '<p><code>&lt;ul&gt;&lt;li&gt;$2&lt;/li&gt;&lt;/ul&gt;</code></p>');
console.log(result);

输出结果:

<p>I have a string</p><p><code>&lt;ul&gt;&lt;li&gt;Content Test 1&lt;/li&gt;&lt;/ul&gt;</code></p>

扩展:处理多条<li>场景

如果用户输入包含多个带&emsp;的<li>,可以分两步处理:

  1. 给所有<li>包裹<ul>并移除多余句号
  2. 批量移除所有<li>前的&emsp;

示例代码:

const originalStr = '<p>I have a string</p><p><code>&lt;li&gt;&amp;emsp;Item 1&lt;/li&gt;&lt;li&gt;&amp;emsp;Item 2&lt;/li&gt;</code>.</p>';
// 第一步:包裹<ul>并去掉句号
let result = originalStr.replace(/(<p><code>)(&lt;li&gt;&amp;emsp;.*?&lt;/li&gt;)+(<\/code>\.)<\/p>/g, '<p><code>&lt;ul&gt;$2&lt;/ul&gt;</code></p>');
// 第二步:批量移除&emsp;
result = result.replace(/&lt;li&gt;&amp;emsp;/g, '&lt;li&gt;');
console.log(result);

输出结果:

<p>I have a string</p><p><code>&lt;ul&gt;&lt;li&gt;Item 1&lt;/li&gt;&lt;li&gt;Item 2&lt;/li&gt;&lt;/ul&gt;</code></p>

注意事项

  • 非贪婪模式.*?确保只匹配单个<li>内的内容,避免跨标签匹配
  • 该方案支持用户输入任意合法文本(包括转义后的HTML标签),完全适配动态内容场景
  • 不同编程语言的正则语法略有差异(如Python的re.sub需指定flags=re.DOTALL处理换行),核心逻辑一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:45:37