
 
 | 
| 技术资料  > ASP技术 > 客户端相关 : 在VBSript中使用regular expression取得子字串 |  
在VBSript中使用regular expression取得子字串 March 25,2004 |  
' 在 VBScript 5 中新增了 regular expression 功能, 
' 但看了微軟的「VBScript 程式語言參考」後確一頭霧水, 
' 而且不同的 Build 版本還有不同的結果, 真是 #%^&!@%&!....。 
' 小弟提供一下範例, 希望對你使用 RegExp 有所幫助, 
' 將此文件儲存成 .vbs 檔可直接執行, 看看結果。 
' 
 
MsgBox "版本: VBScript "&ScriptEngineMajorVersion&" Build:"& ScriptEngineBuildVersion 
 
' 如果你的 VBScript 版本低於 5, 執行下列程式會發生錯誤 
 
Dim s, re, matches, match 
s = "日本時間 11:34:56 , 台北時間 12:34:56。" 
Set re = New RegExp 
 
' 指定 Email 的 pattern 
re.Pattern = "(d+):(d+):(d+)" 
re.Global = True 
Set matches = re.Execute(s) 
 
' Build 號碼 4615 之前的版本可使用下面三範例取得符合的值 
 
 
'範例一: 顯示最後找到的字串 
MsgBox "範例一:" & matches.item(matches.count-1) 
 
'範例二: 把全部找到的字串列出來 
For Each matche In matches 
   MsgBox "範例二:" & matche.value 
Next 
 
'範例三: 
'但()內的子字串在 Build 4615 無法直接取得, 需要靠一些技巧 
'例如取得第一個字串的第三個子字串: 
MsgBox "範例三:" & re.Replace(matches.item(0),"$3") 
 
Set match = Nothing 
 
 
 
' Build 號碼 5014 之後的版本可使用下面三範例取得符合的值 
'但在此 build 之前的版本會發生錯誤 
'可到微軟網站下載最新的 Windows Script 5.5 Beta 2 (目前) 
 
 
'範例四: 顯示首先找到的字串 
Set match = matches(0) 
MsgBox "範例四:" & match 
 
'範例五: 子字串的數量 
MsgBox "範例五:" & match.SubMatches.Count 
 
'範例六: 顯示第一個子字串 
MsgBox "範例六:" & match.SubMatches(0) |  
 
 | 
  
Copyright © 2001-2008 Shenzhen Hiblue Software Team All rights reserved