vbs中的正則表達(dá)式
假定要搜索的字符串是 str="hello world Hello World"
1--規(guī)則基本與dos中的findstr類似。有細(xì)微的差別。如果對(duì)規(guī)則有困惑的,可以在cmd中看看findstr的說(shuō)明就可以了。
2--如何使用?
a--創(chuàng)建類RegExp
set reg=new RegExp
b--類的屬性
reg.pattern---用正則表達(dá)式建立搜索模板
如: reg.pattern="hello"
reg.global=true ---確定是在str中取代全部,還是只取代第一個(gè)匹配項(xiàng)。
reg.replace(str,"x")---把str中的hello用x取代
reg.ignorecase=true---表示不區(qū)分大小寫(xiě)
c--類的方法
set matches=reg.execute(str)---方法execute創(chuàng)建由匹配項(xiàng)組成的集合對(duì)象。
要訪問(wèn)這個(gè)集合對(duì)象就要用語(yǔ)句for each ...next
該集合里面的每一個(gè)對(duì)象有兩個(gè)屬性
屬性1 firstindex屬性,
屬性2 value屬性
如:
1
2
3
|
for each i in matches wscript.echo i.firstindex,i.value next |
最后把上面的和在一起就得到一個(gè)完整的程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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可以不要 ,直接寫(xiě)成 i next ''''for語(yǔ)句也可以用下面的代碼 ''''for i =0 to matches.count-1 '''''' wscript.echo i ,matches(i) '''next |
正則表達(dá)式看過(guò)去看過(guò)來(lái),還是一個(gè)糊涂。
其實(shí)學(xué)習(xí)正則表達(dá)式最好的辦法就是練習(xí)中學(xué)習(xí)。
dos里面的 findstr就是正則表達(dá)式搜索。vbs里也有。
下面的小程序就是vbs編寫(xiě)的學(xué)習(xí)軟件。
只選用了正則表達(dá)式的全局屬。什么是全局屬下?你用了就知道了。
我在這里說(shuō)是空談。
還有在哪里看正則表達(dá)式的規(guī)則?dos的findstr /?
我可以說(shuō),用了包你10分鐘明白什么是正則表達(dá)式。
變生奧為淺顯。
復(fù)制下面的代碼,保存為regtest.vbs 就ok了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
''''************正則表達(dá)式練習(xí)小程序 作者 myzam 2011-2-26******* '''''特別說(shuō)明:只能在cmd中運(yùn)行,否則報(bào)錯(cuò)。 '''''運(yùn)行語(yǔ)法:“cscript+腳本”。 '''''又注,vbs中\(zhòng)b,和dos中的\<,\>相當(dāng),表示一個(gè)單詞 ''''(如word,ath,中國(guó),0852等)的起點(diǎn)和終點(diǎn)。 '''''這是全局設(shè)置的正則表達(dá)式,我用x作為替代了。 set oreg=new regexp wscript.echo "請(qǐng)輸入字符串:" str=wscript.stdin.readline wscript.echo "請(qǐng)輸入正則表達(dá)式:" oreg.pattern=wscript.stdin.readline oreg.global=true '這里設(shè)置的是全局屬性 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 ''''''''======================================== '''附測(cè)試題 '''' 字符串為: the thecome comethecome '''' 模板為:the '''''=========================================== |
這篇文章就介紹到這,希望大家以后多多服務(wù)器之家。