在QTP中进入Tools->Regular Expression Evaluator可以highlight匹配的子串,这个功能很好使用。
Global属性:代表全局匹配
IgnoreCase属性:大小写忽略
Pattern属性:正则表达式
Execute方法:匹配搜索,返回匹配结果集合
Replace方法:匹配代替,返回替代匹配结果
Test方法:测试匹配,返回布尔类型
下面举几个实例:
- '按pattern找到匹配子串和出现的position
- Function RegExpTest(patrn, strng)
- Dim regEx, Match, Matches ' Create variable.
- Set regEx = New RegExp ' Create a regular expression.
- regEx.Pattern = patrn ' Set pattern.
- regEx.IgnoreCase = True ' Set case insensitivity.
- regEx.Global = True ' Set global applicability.
- Set Matches = regEx.Execute(strng) ' Execute search.
- For Each Match in Matches ' Iterate Matches collection.
- 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"))
- '判断正则匹配是否正确
- 'msgbox (IsRegMatch("a123","http://www.123.456.com"))
- Function IsRegMatch(patrn,str)
- Dim regEx
- Set regEx = New RegExp
- regEx.Pattern = patrn
- regEx.IgnoreCase = False
- IsRegMatch = regEx.Test(str)
- Set regEx = nothing
- End Function
- '替换匹配字符串
- 'msgbox (ReplaceRegMatch("9","loader runner 9.0, qtp 9.0","10"))
- Function ReplaceRegMatch(patrn,str,replaceStr)
- Dim regEx
- Set regEx = New RegExp
- regEx.Pattern = patrn
- regEx.IgnoreCase = False
- regEx.Global = True 'false的时候只会替换第一个匹配的字符串。若为true则会替换所有匹配的字符串
- ReplaceRegMatch = regEx.Replace(str,replaceStr)
- End Function
- '返回匹配内容
- 'returnRegMatch "qtp .","qtp 1 qtp 2 qtp3 qtp 4"
- Function ReturnRegMatch(patrn,str)
- Dim regEx,matches,match
- Set regEx = New RegExp
- regEx.Pattern = patrn
- regEx.IgnoreCase = true
- regEx.Global = true '打开全局搜索
- Set matches = regEx.Execute(str)
- For Each match in matches
- print cstr(match.firstIndex) + " " + match.value + " " + cstr(match.length)
- Next
- End Function
正则表达式语法
正则表达式是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为“元字符”)。模式描述在搜索文本时要匹配的一个或多个字符串。
正则表达式示例
表达式 | 匹配 |
/^\s*$/ | 匹配空行。 |
/\d{2}-\d{5}/ | 验证由两位数字、一个连字符再加 5 位数字组成的 ID 号。 |
/<\s*(\S+)(\s[^>]*)?>[\s\S]*<\s*\/\1\s*>/ | 匹配 HTML 标记。 |