首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

一个正则。难,该怎么解决

2013-02-27 
一个正则。。。难function replaceNotInHref(str, word, reword, isGlobal)dim reset re new RegExpre.Patt

一个正则。。。难

function replaceNotInHref(str, word, reword, isGlobal)
dim re
set re = new RegExp
re.Pattern = word & "(?:(?=.*<a\b)|(?!.*?<\/a>))"
re.IgnoreCase = True

re.Global = isGlobal

replaceNotInHref = re.replace(str, reword)
end function

str = "123<a href='f'>金属123</a>金属123<a href='f'>金属</a>123金属"
response.write replaceNotInHref(str, "金属", "被替换了", false)


怎么替换A标签之外的字符
[解决办法]
var str = "123<a href='f'>金属123</a>金属123<a href='f'>金属</a>123金属";
alert(str.replace(/(?=[^>]*(?=<(?!\/)
[解决办法]
$))金属/g,'橡胶'))

[解决办法]
参考下
<%
function replaceNotInHref(str, word, reword, isGlobal)
dim re, i, Matches, Match
set re = new RegExp
re.IgnoreCase = true
re.Global = true
re.Pattern = "(?:<a.*?>[\s\S]*?</a>)"

Set Matches =re.Execute(str)

i = 0
For Each Match in Matches
ReDim Preserve MyArray(i)
MyArray(i) = Match.Value
str = replace(str, Match.Value, "<@#"&i&"#@>")'
i = i + 1
Next

re.Global = isGlobal
re.Pattern = word

str = re.replace(str, reword)

if i > 0 then
for i = 0 to ubound(MyArray)
str = replace(str, "<@#"&i&"#@>", MyArray(i))
next
end if
replaceNotInHref = str
end function

str = "123<a href='f'>金属123</a>金属123<a href='f'>金属</a>123金属"
str1 = "123金属123金属1233"
response.write replaceNotInHref(str, "金属", "被替换了", false)
response.write "<br>"
response.write replaceNotInHref(str1, "金属", "被替换了", true)
%>

[解决办法]
一個有點笨的方法:
先把不需要換的地方換掉,再換需要的地方,最后再把不需要換的地方換回來

var str = "123<a href='f'>金属123</a>金属123<a href='f'>金属</a>123金属";
str = str.replace(/(<a[^>]+>.*?)金属(.*?<\/a>)/ig, "$1xxoo$2").replace(/金属/g, '我暈!').replace(/xxoo/ig, "金属");
alert(str);


也可以簡化一下,先不管那么多,都換掉,然后再把不需要換的地方換回來
看你程序怎麼做更合適

热点排行