qtp中使用正则表达式

在QTP中进入Tools->Regular Expression Evaluator可以highlight匹配的子串,这个功能很好使用。



Vbs提供了针对正则表达式的一个非常实用的类,就是RegExp

Global属性:代表全局匹配

IgnoreCase属性:大小写忽略

Pattern属性:正则表达式

Execute方法:匹配搜索,返回匹配结果集合

Replace方法:匹配代替,返回替代匹配结果

Test方法:测试匹配,返回布尔类型

下面举几个实例:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. '按pattern找到匹配子串和出现的position  
  2. Function RegExpTest(patrn, strng)  
  3.    Dim regEx, Match, Matches   ' Create variable.  
  4.    Set regEx = New RegExp   ' Create a regular expression.  
  5.    regEx.Pattern = patrn   ' Set pattern.  
  6.    regEx.IgnoreCase = True   ' Set case insensitivity.  
  7.    regEx.Global = True   ' Set global applicability.  
  8.    Set Matches = regEx.Execute(strng)   ' Execute search.  
  9.    For Each Match in Matches   ' Iterate Matches collection.  
  10.       RetStr = RetStr & "Match found at position "  
  11.       RetStr = RetStr & Match.FirstIndex & ". Match Value is '"  
  12.       RetStr = RetStr & Match.Value & "'." & vbCRLF  
  13.    Next  
  14.    RegExpTest = RetStr  
  15. End Function  
  16. MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))  
  17.   
  18.   
  19. '判断正则匹配是否正确  
  20.  'msgbox (IsRegMatch("a123","http://www.123.456.com"))  
  21. Function IsRegMatch(patrn,str)  
  22.    Dim regEx  
  23.    Set regEx = New RegExp  
  24.    regEx.Pattern = patrn  
  25.    regEx.IgnoreCase = False  
  26.    IsRegMatch = regEx.Test(str)  
  27.    Set regEx = nothing  
  28. End Function  
  29.    
  30.   
  31. '替换匹配字符串  
  32. 'msgbox (ReplaceRegMatch("9","loader runner 9.0, qtp 9.0","10"))  
  33. Function ReplaceRegMatch(patrn,str,replaceStr)  
  34.    Dim regEx  
  35.    Set regEx = New RegExp  
  36.    regEx.Pattern = patrn  
  37.    regEx.IgnoreCase = False  
  38.    regEx.Global = True   'false的时候只会替换第一个匹配的字符串。若为true则会替换所有匹配的字符串  
  39.    ReplaceRegMatch = regEx.Replace(str,replaceStr)  
  40. End Function  
  41.   
  42.   
  43. '返回匹配内容  
  44. 'returnRegMatch "qtp .","qtp 1 qtp 2 qtp3 qtp 4"  
  45. Function ReturnRegMatch(patrn,str)  
  46.    Dim regEx,matches,match  
  47.    Set regEx = New RegExp  
  48.    regEx.Pattern = patrn  
  49.    regEx.IgnoreCase = true  
  50.    regEx.Global = true  '打开全局搜索  
  51.    Set matches = regEx.Execute(str)  
  52.    For Each match in matches  
  53.            print cstr(match.firstIndex) + " " + match.value + " " + cstr(match.length)  
  54.    Next  
  55. End Function  

正则表达式语法

正则表达式是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为“元字符”)。模式描述在搜索文本时要匹配的一个或多个字符串。

正则表达式示例

表达式

匹配

/^\s*$/

匹配空行。

/\d{2}-\d{5}/

验证由两位数字、一个连字符再加 5 位数字组成的 ID 号。

/<\s*(\S+)(\s[^>]*)?>[\s\S]*<\s*\/\1\s*>/

匹配 HTML 标记。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值