15分钟学会vbscript中的正则表达式

vbs中的正则表达式

假定要搜索的字符串是 str="hello world Hello World"

1--规则基本与dos中的findstr类似。有细微的差别。如果对规则有困惑的,可以在cmd中看看findstr的说明就可以了。
2--如何使用?
a--创建类RegExp
set reg=new RegExp

b--类的属性
reg.pattern---用正则表达式建立搜索模板
如: reg.pattern="hello"
reg.global=true ---确定是在str中取代全部,还是只取代第一个匹配项。
reg.replace(str,"x")---把str中的hello用x取代
reg.ignorecase=true---表示不区分大小写

c--类的方法

set matches=reg.execute(str)---方法execute创建由匹配项组成的集合对象。
要访问这个集合对象就要用语句for each ...next
该集合里面的每一个对象有两个属性
属性1 firstindex属性,
属性2 value属性
如:

for each i in matches 
  wscript.echo i.firstindex,i.value
 next

最后把上面的和在一起就得到一个完整的程序如下:

set reg=new regexp
str="hello world Hello World"
reg.pattern="hello"
reg.ignorecase=true
reg.global=true
set matches=reg.execute(str)
regstr=reg.replace(str,"x")
wscript.echo regstr
for each i in matches
 wscript.echo i.firstindex,i.value '‘'‘'value可以不要 ,直接写成 i 
next
''''for语句也可以用下面的代码
''''for i =0 to matches.count-1
'''''' wscript.echo i ,matches(i)
'''next

正则表达式看过去看过来,还是一个糊涂。
其实学习正则表达式最好的办法就是练习中学习。
dos里面的 findstr就是正则表达式搜索。vbs里也有。
下面的小程序就是vbs编写的学习软件。
只选用了正则表达式的全局属。什么是全局属下?你用了就知道了。
我在这里说是空谈。
还有在哪里看正则表达式的规则?dos的findstr /?
我可以说,用了包你10分钟明白什么是正则表达式。
变生奥为浅显。
复制下面的代码,保存为regtest.vbs 就ok了。

''''************正则表达式练习小程序 作者 myzam 2011-2-26*******
'''''特别说明:只能在cmd中运行,否则报错。
'''''运行语法:“cscript+脚本”。
'''''又注,vbs中b,和dos中的<,>相当,表示一个单词
''''(如word,ath,中国,0852等)的起点和终点。
'''''这是全局设置的正则表达式,我用x作为替代了。
set oreg=new regexp

wscript.echo "请输入字符串:"
str=wscript.stdin.readline

wscript.echo "请输入正则表达式:"
oreg.pattern=wscript.stdin.readline
oreg.global=true '这里设置的是全局属性
set matches=oreg.execute(str)
wscript.echo oreg.replace(str,"x")
for matche=o to matches.count-1
 wscript.echo "index= "&matche,"-------value= "&matches(matche)
next

''''''''========================================
'''附测试题
'''' 字符串为: the thecome comethecome
'''' 模板为:the
'''''===========================================

这篇文章就介绍到这,希望大家以后多多来客网。