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