如何添加防止正则表达式解析字符串的某些部分

How do I add prevent my regex from parsing certain parts of a string?

本文关键字:字符串 些部 正则表达式 何添加 添加      更新时间:2023-09-26

根据这个答案,我正在使用replaceAll()函数交换javascript(Node)应用程序中的任意字符串:

this.replaceAll = function(str1, str2, ignoreCase)
{
    return this.replace(new RegExp(str1.replace(/(['/','!'''^'$'{'}'[']'(')'.'*'+'?'|'<'>'-'&])/g,"''$&"),(ignoreCase?"gi":"g")),(typeof(str2)=="string")?str2.replace(/'$/g,"$$$$"):str2);
}

我想扩展这个正则表达式,这样它就可以而不是尝试匹配一组<span>...</span>标记内的任何。(我需要在一些字符串的部分周围添加HTML Span标记,如果模式重复[例如,字符串"Foobarbaz"中的"Foo"answers"Foobar"],我不想在Span中包装任何东西两次

我在一个字符串上运行多个regex搜索/替换,我想确保没有任何内容被多次处理。

我的理解是,我会以某种方式需要一个[<SPAN>] ... [</SPAN>],但我不太确定具体细节。有什么建议吗?

我不明白你的regexp是做什么的,但一般来说,技术是这样的:

html = "replace this and this but not <span> this one </span> or <b>this</b> but this is fine"
// remove parts you don't want to be touched and place them in a buffer
tags = []
html = html.replace(/<('w+).+?<'/'1>/g, function($0) {
    tags.push($0)
    return '@@' + (tags.length - 1)
})
// do the actual replacement
html = html.replace(/this/g, "that")
// put preserved parts back
html = html.replace(/@@('d+)/g, function($0, $1) {
    return tags[$1]
})