【问题标题】:RegEx negative lookahead matches only one character正则表达式负前瞻仅匹配一个字符
【发布时间】:2019-11-26 08:49:16
【问题描述】:

我写了一个正则表达式,它应该匹配除<span style="background-color: #any-color"></span> 之外的所有危险HTML 字符:

((?!<span style="background-color: #([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})">|<\/span>)[&<>"'/])

但是,它与我排除的额外字符匹配。
这里 RegEx 不应该匹配引号 style="background-color:,但它匹配:

我在哪里做错了?

Regex101 demo。这里是link to the current project

function escapeHtml(in_) {
    return in_.replace(/((?!<span style="background-color: #([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})">|<\/span>)[&<>"'/])/g, s => {
        const entityMap = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            '\'': '&#39;',
            '/': '&#x2F;',
        };

        return entityMap[s];
    });
}

【问题讨论】:

  • 你要删除那些“危险的 HTML 字符”吗?
  • @WiktorStribiżew 不,我要转义这些字符。我知道在这样的操作之后,将它们插入标签主体以外的任何地方仍然很危险,但我将在那里插入生成的字符串。
  • 这在没有 hack 的常规文本编辑器中不太可能。 This is a PCRE regex solution.
  • You should not use regular expressions to parse HTML。如果你打算使用 Javacript,为什么不使用内置函数呢?
  • @Seblor 这个问题与 HTML 解析无关。

标签: regex regex-negation


【解决方案1】:

请注意,只有当您完全控制纯文本字符串中出现的实体时,您才能使用正则表达式

因此,如果您手动添加 &lt;/span&gt;&lt;span style="background-color: #aaff11"&gt; 之类的字符串,您可以像这样修复您的代码:

function escapeHtml(in_) {
	return in_.replace(/(<span style="background-color: #(?:[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})">|<\/span>)|[&<>"'\/]/g, ($0,$1) => {
		const entityMap = {
			'&': '&amp;',
			'<': '&lt;',
			'>': '&gt;',
			'"': '&quot;',
			'\'': '&#39;',
			'/': '&#x2F;',
		};
		return $1 ? $1 : entityMap[$0];
	});
}
console.log(escapeHtml('<b>some test <span style="background-color: #333300">ol string!</b></span> nope <i>whoops</i> <span style="background-color: #ff0000">meh</span>'));

否则,您需要考虑一种 DOM 解析方法。见Parse an HTML string with JS

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多