ASP 中也可以用Regex,為了方便使用,對Regex操作進行了封裝,目前只封裝了兩個:
1、正則替換
'功能:通過Regex替換字串
'參數: str 原字串
' patton 正則匹配運算式
' restr 替換字串
' op 選項 含有i忽略大小寫,
' 含有g表示全域匹配,一般用法"ig"
'返回:替換後的字串
'舉例:regReplace("ss5ss6s7s","\d","","ig") 返回 ssssss
Public Function regReplace(str,patton,restr,op)
dim RegEx : Set RegEx = New RegExp
if instr(op,"i") > 0 then
RegEx.IgnoreCase =true
end if
if instr(op, "g") > 0 then
regEx.Global = true
end if
RegEx.Pattern = patton
regReplace=RegEx.replace(str,restr)
set RegEx = nothing
End Function
用法舉例:如剔除一個字串中所有的html標籤
str = "dddffffdddd<script>ssssss</script><html></html><body></body> <></> <sss></sss>"
response.Write regReplace(str, "<(.*).+>.*<\/\1>", "","ig")
2、正則檢測
'功能:通過Regex檢測運算式是否包含字串
'參數: str 原字串
' patton 正則匹配運算式
' op 選項 含有i忽略大小寫,
' 含有g表示全域匹配,一般用法"ig"
'返回:是否有匹配
'舉例:regReplace("ss5ss6s7s","\d","ig") 返回 true
Public Function regTest(str,patton,op)
dim RegEx : Set RegEx = New RegExp
if instr(op,"i") > 0 then
RegEx.IgnoreCase =true
end if
if instr(op, "g") > 0 then
regEx.Global = true
end if
RegEx.Pattern = patton
regTest=RegEx.test(str)
set RegEx = nothing
End Function
用法舉例:檢測一個字串中是否有html字串
str = "dddffffdddd<script>ssssss</script><html></html><body></body> <></> <sss></sss>"
response.Write regReplace(str, "<(.*).+>.*<\/\1>", "ig")