最近在寫一個簡單的轉換程序,即將10.190.10.162之類的字符串轉換成一個整數。我的思路很簡單,提取出用"."符號分隔的四個數n1,n2,n3,n4,轉換的結果=n1*256^3+n2*256^2+n3*256+n4。提取的方法首先想到的是正則表達式。於是:
Dim objRegExp As RegExp
Dim objMatch As Match
Dim colMatches As MatchCollection
Dim pt As String
Dim nip As Double
pt = "/b(?<n1>/d{1,3})/.(?<n2>/d{1,3})/.(?<n3>/d{1,3})/.(?<n4>/d{1,3}/b)"
Set objRegExp = New RegExp
objRegExp.Pattern = pt
objRegExp.Global = True
If (objRegExp.Test(ipstr) = True) Then
Set colMatches = objRegExp.Execute(ipstr)
For Each objMatch In colMatches '' Iterate Matches collection.
Dim n1
Dim n2, n3, n4 As Long
Dim x As Long
Dim t As Long
x = 256 ^ 3
t = CLng(objMatch.SubMatches(0))
n1 = CDec(t) * CDec(x)
n2 = CLng(objMatch.SubMatches(1)) * 256 * 256
n3 = objMatch.SubMatches(2) * 256
n4 = objMatch.SubMatches(3)
nip = n1 + n2 + n3 + n4
Next
end if
正則表達式用了分組捕獲,這是我常用的,原來在.net裏C#的一個項目用過,寫法沒有問題。但是這裏....。運行後,在執行objRegExp.Test(ipstr) 時出現了錯誤。多方調試後仍不行。乾脆先從最簡單的捕獲試吧。試着把正則表達式寫成"/b(/d{1,3})/.(/d{1,3})/.(/d{1,3})/.(/d{1,3}/b)",隨後運行成功!
按理說正則表達式對不同的編程語言是相類似的,但具體的實現會有些差異,一種語言環境下寫的表達式在另一種語言環境可能不成立,就象這個例子。