当前位置: 移动技术网 > IT编程>脚本编程>VBScript > VBS教程:对象-正则表达式(RegExp)对象

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

万通商聊,借贷宝不雅视频下载,218.206.202.110

正则表达式(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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网