Vbscript正则表达式实例及在QTP中应用

发表于:2009-2-23 13:18

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:tester2009    来源:51Testing博客

  一、实例:

  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.*"

21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号