作者:阿賴 (Email: A at Lai.com.cn 首頁:http://www.9499.net Blog: http://blog.csdn.net/laily/ )
關鍵字:Regex VB VBSCRIPT Javascript
摘要:javascriptRegex到VBScriptRegex的轉換,兼談VB裡Regex的用法。
之前用javascript寫過將路徑拆分為根目錄和子目錄串的Regex演算法。因項目需要將同樣的功能用VBScript寫出來。下面是原來寫JSScript的程式:
//purpose:to setparate the path string into two part:the root and the subfolder
// ie.
// c:/aa/bb/cc => c:/ + aa/bb/cc
// //aa/bb/cc => //aa + bb/cc
// http://www.9499.net => http:// + www.9499.net
var strRoot,strSub
var re=/^([^//^//]+[////]+|////[^//]+)(.*)$/
if(re.test(strFolder))
{
strRoot=RegExp.$1
strSub=RegExp.$2
}
由於Javascript語言整合了Regex的功能,寫起來感覺順暢自然。而VB6裡要使用Regex只能通過組件對象調用的形式來調用VBScript的Regex功能。在VB6的IDE裡選擇project(項目)->references(引用),找到並選上Microsoft VBSCript Regular Expression。注意到這個裡面有兩個版本可供選擇,一個是1.0,另一個是5.5,我們當然選擇5.5了。這兩個版本的區別是1.0比5.5少了子匹配submatchs的功能。如果選1.0的話是實現不了上面這段javascript代碼的功能的,因為其中關鍵之處就是用到了子匹配submatchs。
下面就是跟上面jscript同樣功能的vbscript的程式碼:
'purpose:to setparate the path string into two part:the root and the subfolder
' ie.
' c:/aa/bb/cc => c:/ + aa/bb/cc
' //aa/bb/cc => //aa + bb/cc
' http://www.9499.net => http:// + www.9499.net
Dim strRoot, strSub
Dim regPathParse
Dim reMatch, reMatchCol, reSubMatch
re.Pattern = "^([^//^//]+[////]+|////[^//]+)(.*)$"
Set reMatchCol = re.Execute(strFolder)
If reMatchCol.Count = 1 Then
Set reMatch = reMatchCol(0)
Set reSubMatch = reMatch.SubMatches
If reSubMatch.Count = 2 Then
strRoot = reSubMatch(0)
strSub = reSubMatch(1)
End If
End If
怎麼樣,jscriptRegex的寫法是不是比VBS簡潔很多呢。