您的位置:首页 > 编程语言 > VB

VBS教程:对象-正则表达式(RegExp)对象

2006-11-16 00:00 1626 查看

正则表达式(RegExp)对象
提供简单的正则表达式支持功能。

说明
下面的代码说明了RegExp对象的用法:

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   ' 遍历匹配集合。
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"))

RegExp对象在VBScript中提供正则表达式支持功能,该对象有3个属性和3个方法。

1)Execute方法

该方法用于对指定正则表达式进行匹配检测,其值返回一个Matches集合,其中包含了所有检测到匹配的Match对象。如果没有检测到任何匹配则返回一个空的Matches集合。

语法格式:regexp.Execute(string)
其中,regexp为RegExp对象的变量名称;string为要进行匹配检测的有效字符串表达式。

2)Replace方法

调用Replace方法时,如果在指定字符串中找到与指定正则表达式相匹配的字符(串),则用指定的其他字符(串)进行替换。该方法的返回值为替换以后的字符串表达式。

语法格式:regexp.Replace(string1,string2)
其中,regexp为RegExp对象的变量名称;string1为要被检测并替换的字符串表达式;string2为用于替换的字符串表达式。

sub window_onLoad()
dim str,regexp
dim msgstr
str="How are you"

msgstr="替换前:"&str&"<br />"
'//创建RegExp对象
set regexp=new RegExp
'//设置正则表达式

regexp.Pattern="o."
'//设置是否替换所有匹配
regexp.Global=True
document.write msgstr
'//替换操作

msgstr=regexp.Replace(str,"test")
msgstr="替换后:"&msgstr
document.write msgstr
end sub

3)Test方法

该方法的作用是判断指定的字符串中是否有与指定的正则表达式相匹配的内容。如果有,则返回Ture;否则返回False。同Replace方法类似,调用该法时,正则表达式是由Pattern属性指定的。二者不同在于,Global属性的设置对该方法没有影响。

sub window_onLoad()
dim str,regexp
dim blvar
str="This is a test"

'//创建RegExp对象
set regexp=new RegExp
'//设置正则表达式
regexp.Pattern=".s"

'//调用Test方法
blvar=regexp.Test(str)
if blvar then
document.write "在"&str&"中找到了与"®exp.pattern&"相匹配的内容"

else
document.write "没有找到匹配内容"
end if
end sub

这篇文章就介绍到这,需要的朋友可以参考一下。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  VBS RegExp 对象