路漫漫其修远兮,吾将上下而求索

vbs正则表达式的几个函数

上一篇 / 下一篇  2011-08-13 19:18:34 / 个人分类:Qtp

以前一直没有好好的学过,这次整理一下。

正则中/d+就是代表一个或多个数字,用这个做例子。

RegExp就是建立正则的对像。如Set regEx = New RegExp。regEx.Pattern 就是来设置正则的模式的,如

regEx.Pattern ="/d+"。regEx.IgnoreCase = True   ' 设置是否区分大小写。regEx.Global = True   ' 设置全程可用性。

RegExp对像有3种方法,分别是execute、test、replace。

test方法是对指定的字符串执行一个正则表达式搜索,并返回一个Boolean值指示是否找到匹配的模式。RegExp.Global属性对Test方法没有影响。如果找到了匹配的模式,Test方法返回True;否则返回False

例子:

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(str,patrn, replStr)
Dim regEx, str1               ' 建立变量。
'str1 = "dog 123."
Set regEx = New RegExp               ' 建立正则表达式。
regEx.Pattern = patrn               ' 设置模式。
regEx.IgnoreCase = True               ' 设置是否区分大小写。
ReplaceTest = regEx.Replace(str, replStr)         ' 作替换。
End Function

MsgBox(ReplaceTest("dog 123","\d+", "cat")) '将字符串中的123替换为cat

Execute 方法,则是对指定的字符串执行正则表达式搜索。这里又涉及到Match对像和Matches 集合。Matches 集合就是match的对像集合。Matches集合中包含若干独立的Match对象,只能使用RegExp对象的Execute方法来创建之。例子:


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      ' 遍历 Matches 集合。
      RetStr = RetStr & Match.FirstIndex & "。匹配的长度为"&" "
RetStr = RetStr & Match.Length &" "
      RetStr = RetStr & Matches(0) &" "      '值为123
     RetStr = RetStr & Matches(1)&" "      '值为44
    RetStr = RetStr & Match.value&" "    '值为123和44的数组
     RetStr = RetStr & vbCRLF
   Next
   RegExpTest = RetStr
End Function
MsgBox(RegExpTest("\d+", "123a44"))


TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-12  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 40461
  • 日志数: 76
  • 图片数: 2
  • 建立时间: 2007-11-02
  • 更新时间: 2011-08-13

RSS订阅

Open Toolbar