一、实例:
Function RegExpTest(patrn, strng) Dim regEx, Match, Matches ' 建立变量。 Set regEx = New RegExp ' 建立正则表达式。 regEx.Pattern = patrn ' 设置模式。 regEx.IgnoreCase = True ' 设置不区分字符大小写。如果设置成 false 则区分大小小写 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 = RetStr End Function MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4")) |
运行结果:
二、在QTP中应用实例:
正则表达式在自动化测试中可以起到意想不到的效果,例如,测试QTP的“Flight”程序时,在如图(下)所示的的选择航班的功能界面中,录制测试脚本。
这里对WinList控件的操作使用的是Select方法,但是需要指定一长串的字符串,例如下代码:
Function SelectRegExp(Obj,Patrn,Button,Offset) Dim NumOfItems,i,CurrentValue,regEx,ItemToSelect,oldFilter '初始化正则表达式 Set regEx=new RegExp regEx.pattern=patrn regEx.Ignorecase=false '区分大小写 ldfilter=Reporter.Filter '保存默认值 Reporter.Filter=2 '仅发送错误 ItemToSelect=-1 '获取测试对象的 NumOfItems属性 NumOfItems=Obj.getroproperty("items count") For i=0 to NumOfItems-1 CurrentValue=Obj.GetItem(i) If regEx.test(CurrentValue)Then If (ItemToselect<>-1) Then SelectRegExp=-1 '表示匹配项不唯一 Reporter.Filter=oldFilter Exit function End If ItemToSelect=i End If Next Reporter.Filter=oldFilter '重置默认设置 '做出选择动作 If (ItemToSelect>=0) Then SelectRegExp=Obj.Select(ItemToSelect,Button,Offset) else SelectRegExp=-1 End If End Function |
利用”RegisterUserFunc“把SelectRegExp函数注册注册到WinList控件的Select方法后,就可以使用重用后的方法,如以下代码:
'重写WinList控件的Select方法 RegisterUserFunc"WinList","select","SelectRegExp" '使用重写后的WinList控件的Select方法 Window("Flight Reservation").Dialog("Flights Table").Activate Window("Flight Reservation").Dialog("Flights Table").WinList("From").select "15797.*" |