RegExp就是建立正則的對(duì)像。
如:
Set regEx = New RegExp
regEx.Pattern 就是來(lái)設(shè)置正則的模式的,
如:
regEx.Pattern ="/d+"
regEx.IgnoreCase = True ' 設(shè)置是否區(qū)分大小寫(xiě)
regEx.Global = True ' 設(shè)置全程可用性。
RegExp對(duì)像有3種方法,分別是execute、test、replace。
test方法是對(duì)指定的字符串執(zhí)行一個(gè)正則表達(dá)式搜索,并返回一個(gè) Boolean 值指示是否找到匹配的模式。RegExp.Global屬性對(duì)Test方法沒(méi)有影響。如果找到了匹配的模式,Test方法返回True;否則返回False。
例子:
測(cè)試的時(shí)候,msgbox是vbs的用法,如果是asp文件,需要將msgbox替換為response.write
復(fù)制代碼 代碼如下:
Function RegExpTest(patrn, strng)
Dim regEx, retVal ' 建立變量。
Set regEx = New RegExp ' 建立正則表達(dá)式。
regEx.Pattern = patrn ' 設(shè)置模式。
regEx.IgnoreCase = False ' 設(shè)置是否區(qū)分大小寫(xiě)。
retVal = regEx.Test(strng) ' 執(zhí)行搜索測(cè)試。
If retVal Then
RegExpTest = "找到一個(gè)或多個(gè)匹配。"
Else
RegExpTest = "未找到匹配。"
End If
End Function
MsgBox(RegExpTest("\d+", "abcd1234"))
MsgBox(RegExpTest("\d+", "abcd"))
Replace 方法替換在正則表達(dá)式查找中找到的文本
例子:
vbs代碼
復(fù)制代碼 代碼如下:
Function ReplaceTest(str,patrn, replStr)
Dim regEx, str1 ' 建立變量。
'str1 = "dog 123."
Set regEx = New RegExp ' 建立正則表達(dá)式。
regEx.Pattern = patrn ' 設(shè)置模式。
regEx.IgnoreCase = True ' 設(shè)置是否區(qū)分大小寫(xiě)。
ReplaceTest = regEx.Replace(str, replStr) ' 作替換。
End Function
MsgBox(ReplaceTest("dog 123","\d+", "cat")) '將字符串中的123替換為cat
Execute 方法,則是對(duì)指定的字符串執(zhí)行正則表達(dá)式搜索。這里又涉及到Match對(duì)像和Matches 集合。Matches 集合就是match的對(duì)像集合。Matches 集合中包含若干獨(dú)立的 Match 對(duì)象,只能使用 RegExp 對(duì)象的 Execute 方法來(lái)創(chuàng)建之。例子:
vbs測(cè)試代碼
復(fù)制代碼 代碼如下:
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches ' 建立變量。
Set regEx = New RegExp ' 建立正則表達(dá)式。
regEx.Pattern = patrn ' 設(shè)置模式。
regEx.IgnoreCase = True ' 設(shè)置是否區(qū)分大小寫(xiě)。
regEx.Global = True ' 設(shè)置全程可用性。
Set Matches = regEx.Execute(strng) ' 執(zhí)行搜索。
For Each Match in Matches ' 遍歷 Matches 集合。
RetStr = RetStr Match.FirstIndex "。匹配的長(zhǎng)度為"" "
RetStr = RetStr Match.Length " "
RetStr = RetStr Matches(0) " " '值為123
RetStr = RetStr Matches(1)" " '值為44
RetStr = RetStr Match.value" " '值為123和44的數(shù)組
RetStr = RetStr vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("\d+", "123a44"))
您可能感興趣的文章:- Javascript中使用exec進(jìn)行正則表達(dá)式全局匹配時(shí)的注意事項(xiàng)
- js正則表達(dá)式之exec方法講解
- js正則表達(dá)式中test,exec,match方法的區(qū)別說(shuō)明
- js正則表達(dá)式test()和exec()用法實(shí)例
- 在JavaScript的正則表達(dá)式中使用exec()方法
- js正則表達(dá)式中exec用法實(shí)例
- 使用正則表達(dá)式 exec 獲取字符串中的漢字