Function Validate(strng,patrn) Dim regEx Set regEx = New RegExp regEx.Pattern = patrn regEx.IgnoreCase = True regEx.Global = True Validate = regEx.test(strng) Set regEx = Nothing End Function
使用例子
If Validate(Fdr.Name,"F\d{4}_P\d{4}")=True Then ... ... End If
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執行]
2、替換功能
復制代碼 代碼如下:
'========================== '用正則表達式實現替換 '========================== function replaceregex(patern,str,tagstr) dim regex,matches set regex=new regExp regex.pattern=patern regex.IgnoreCase=true regex.global=true matches=regex.replace(str,tagstr) replaceregex=matches end function
Function RegExpTest(patrn, strng) Dim regEx, retVal ' 建立變量。 Set regEx = New RegExp ' 建立正則表達式。 regEx.Pattern = patrn ' 設置模式。 regEx.IgnoreCase = False ' 設置是否區分大小寫。 retVal = regEx.Test(strng) ' 執行搜索測試。 If retVal Then RegExpTest = "找到一個或多個匹配。" Else RegExpTest = "未找到匹配。" End If End Function MsgBox(RegExpTest("\d+", "abcd1234")) MsgBox(RegExpTest("\d+", "abcd"))
Replace 方法替換在正則表達式查找中找到的文本,例子:
復制代碼 代碼如下:
Function ReplaceTest(patrn, replStr) Dim regEx, str1 ' 建立變量。 str1 = "dog 123." Set regEx = New RegExp ' 建立正則表達式。 regEx.Pattern = patrn ' 設置模式。 regEx.IgnoreCase = True ' 設置是否區分大小寫。 ReplaceTest = regEx.Replace(str1, replStr) ' 作替換。 End Function