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

时间:2013-12-11 19:48:45

标签: javascript regex

As per this answer,我正在使用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标记,并且我不想在span 两次中包装任何内容,如果模式会重复[Ie,'Foo'和'Foobar'在字符串“Foobarbaz”])

我在一个字符串上运行多个正则表达式搜索/替换,我想确保没有多次处理。

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

1 个答案:

答案 0 :(得分:1)

我不明白你的正则表达式是做什么的,但一般来说技术是这样的:

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]
})
相关问题