VBS基础篇 - RegExp 对象

正则表达式( 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 '循环遍历Matches集合   
    RetStr = RetStr & "Match found at position "    
    RetStr = RetStr & Match.FirstIndex & ". Match Value is '"    
    RetStr = RetStr & Match.Value & "'." & vbCRLF  
Next  RegExpTest = RetStrEnd FunctionMsgBox(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

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值