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

如何使用正则替换HTML文本中除属性值包裹外的所有双引号

解决方案

匹配用正则表达式

你可以用以下正则匹配所有需要替换的非HTML属性双引号:

"(?![^<]*>)

正则逻辑说明

核心使用负向先行断言(?![^<]*>),规则为:只匹配后面不会出现「无左尖括号<前提下直接遇到右尖括号>」情况的双引号,天然排除了所有在<>包裹的HTML标签内部的属性双引号。

代码实现示例

JavaScript 实现

const originStr = `<a href="#" class="name">here is "quoted"</a> and another in "quote" and alone quote - ".`;
const processedStr = originStr.replace(/"(?![^<]*>)/g, '&quot;');
console.log(processedStr);

Python 实现

import re

origin_str = '<a href="#" class="name">here is "quoted"</a> and another in "quote" and alone quote - ".'
processed_str = re.sub(r'"(?![^<]*>)', '&quot;', origin_str)
print(processed_str)

输出效果

运行代码后得到的结果和你预期一致:

<a href="#" class="name">here is &quot;quoted&quot;</a> and another in &quot;quote&quot; and alone quote - &quot;.

注意事项

该方案仅适用于语法基本合规的HTML内容,若输入的HTML存在标签未闭合、属性引号不配对等语法错误,可能会出现匹配偏差。

内容的提问来源于stack exchange,提问作者michal.jakubeczy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:45:03