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屬性
如:
1
2
3
|
for each i in matches wscript.echo i.firstindex,i.value next |
最后把上面的和在一起就得到一個完整的程序如下:
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可以不要 ,直接寫成 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了。
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
|
''''************正則表達式練習小程序 作者 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 '''''=========================================== |
這篇文章就介紹到這,希望大家以后多多服務器之家。