[英]How do I add prevent my regex from parsing certain parts of a string?
As per this answer , I am making use of a replaceAll()
function to swap arbitrary strings in my javascript (Node) application: 按照这个答案 ,我正在使用
replaceAll()
函数在我的javascript(节点)应用程序中交换任意字符串:
this.replaceAll = function(str1, str2, ignoreCase)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignoreCase?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
I would like to expand this regex, such that it does not try to match anything inside a set of <span>...</span>
tags. 我想扩大这个表达式,这样它不会试图一组内匹配任何
<span>...</span>
标记。 (I need to add HTML Span tags around parts of some strings, and I don't want to wrap anything in a span twice , if the patterns would duplicate [Ie, 'Foo' and 'Foobar' in the string "Foobarbaz"]) (我需要添加周围的一些字符串的部分HTML跨度标签,而我不想来包装一个跨度东西两次 ,如果模式将[字符串“Foobarbaz”在IE中,“富”和“Foobar的”]复制)
I am running multiple regex search/replaces on a single string, and I want to make sure that nothing gets processed multiple times. 我正在单个字符串上运行多个正则表达式搜索/替换,并且我想确保没有任何东西被处理多次。
My understanding is that I'll need a [<SPAN>] ... [</SPAN>]
somehow, but I'm not quite sure on the specifics. 我的理解是,无论如何我都需要
[<SPAN>] ... [</SPAN>]
,但是我不确定具体细节。 Any advice? 有什么建议吗?
I don't understand what your regexp does, but in general the technique is like this: 我不了解您的正则表达式会做什么,但总的来说,这种技术是这样的:
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]
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.