正則表達式(RegExp)對象
提供簡單的正則表達式支持功能。
說明
下面的代碼說明了RegExp對象的用法:
Function RegExpTest(patrn, strng) Dim regEx, Match, Matches ' 建立變量。 Set regEx = New RegExp ' 建立正則表達式。 regEx.Pattern = patrn ' 設置模式。 regEx.IgnoreCase = True ' 設置是否區分字符大小寫。 regEx.Global = True ' 設置全局可用性。 Set Matches = regEx.Execute(strng) ' 執行搜索。 For Each Match in Matches ' 遍歷匹配集合。 RetStr = RetStr & "Match found at position " RetStr = RetStr & Match.FirstIndex & ". Match Value is '" RetStr = RetStr & Match.Value & "'." & vbCRLF Next RegExpTest = RetStrEnd FunctionMsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))
RegExp對象在VBScript中提供正則表達式支持功能,該對象有3個屬性和3個方法。
1)Execute方法
該方法用于對指定正則表達式進行匹配檢測,其值返回一個Matches集合,其中包含了所有檢測到匹配的Match對象。如果沒有檢測到任何匹配則返回一個空的Matches集合。
語法格式:regexp.Execute(string)
其中,regexp為RegExp對象的變量名稱;string為要進行匹配檢測的有效字符串表達式。
2)Replace方法
調用Replace方法時,如果在指定字符串中找到與指定正則表達式相匹配的字符(串),則用指定的其他字符(串)進行替換。該方法的返回值為替換以后的字符串表達式。
語法格式:regexp.Replace(string1,string2)
其中,regexp為RegExp對象的變量名稱;string1為要被檢測并替換的字符串表達式;string2為用于替換的字符串表達式。
sub window_onLoad() dim str,regexpdim msgstrstr="How are you"msgstr="替換前:"&str&"<br />"'//創建RegExp對象set regexp=new RegExp'//設置正則表達式regexp.Pattern="o."'//設置是否替換所有匹配regexp.Global=Truedocument.write msgstr'//替換操作msgstr=regexp.Replace(str,"test")msgstr="替換后:"&msgstrdocument.write msgstrend sub
3)Test方法
該方法的作用是判斷指定的字符串中是否有與指定的正則表達式相匹配的內容。如果有,則返回Ture;否則返回False。同Replace方法類似,調用該法時,正則表達式是由Pattern屬性指定的。二者不同在于,Global屬性的設置對該方法沒有影響。
sub window_onLoad() dim str,regexpdim blvarstr="This is a test"'//創建RegExp對象set regexp=new RegExp'//設置正則表達式regexp.Pattern=".s"'//調用Test方法blvar=regexp.Test(str)if blvar then document.write "在"&str&"中找到了與"®exp.pattern&"相匹配的內容"else document.write "沒有找到匹配內容" end ifend sub
這篇文章就介紹到這,需要的朋友可以參考一下。
新聞熱點
疑難解答