首先,您可能想知道输出的性质。您需要知道如何验证 IP 地址的字符串。
IP 地址的元素将成为您需要测试的条件。
- 4段
- 由点分隔符分隔
- 每个段的编号范围从下限 => 0 到上限 <= 255
这是基本的。但实际上以下用于验证 IP 地址:-
The first number cannot be 10.
If the first number is 172, the second number cannot be between 16 and 31 (inclusive).
If the first number is 192, the second number cannot be 168.
None of the numbers can be greater than 255.
在我的示例代码中,我不会遵循严格的 IP 验证参数,而是遵循基础知识。
如果您使用的是 VBA,您仍然可以使用Split
方法。在此处查看拆分文档。
使用时Split
,可以使用分隔符。可以是从 [az] 到 [0-9] 到特殊字符 [,;'@]...
选项显式
Sub validateIP()
Dim strTrash As String
Dim varDelimited As Variant
Dim varDotDelimited As Variant
Dim i As Integer, j As Integer, trueCounter As Integer
'--in your case in between each of the IP address and other combinations, has a white space
strTrash = "00:87:90:65:67:98 192.165.32.23 192.165.32.23 vlan.10 none"
'--first delimit by white space using Split
varDelimited = Split(strTrash, " ")
'-- loop through variant array
For i = LBound(varDelimited) To UBound(varDelimited)
'--validate if delimited strings are starting and ending with a number and if string contains a dot
If IsNumeric(Left(varDelimited(i), 1)) And IsNumeric(Right(varDelimited(i), 1)) And InStr(varDelimited(i), ".") Then
'--validate for IP address type
'--delimit by dot
varDotDelimited = Split(varDelimited(i), ".")
'--validate for 4 segments : Split results in zero-indexed arrays
If UBound(varDotDelimited) = 3 Then
'--set trueCounter to zero
trueCounter = 0
'--validate each segment for a number between 0 and 255
For j = LBound(varDotDelimited) To UBound(varDotDelimited)
If IsNumeric(varDotDelimited(j)) And CInt(varDotDelimited(j)) >= 0 And CInt(varDotDelimited(j)) <= 255 Then
'--you can either save data into an array or any collection object and dump them later on to sheet
'--or simply throw a message box each time you find a valid IP address from Trash
trueCounter = trueCounter + 1
End If
Next j
If trueCounter = 4 Then
MsgBox varDelimited(i) & " is a valid IP Address"
End If
End If
End If
Next i
End Sub
另一种验证方法是使用Regex
. 如果您有兴趣,可以稍后查看。
Sub validateIPRegex()
Dim strTrash As String
Dim objRegEx As Object
Dim matchedIPs As Object
Dim i As Integer
Dim allIPs As String
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
objRegEx.MultiLine = False
'--this pattern doesn't consider 255. Just any 1 to 3 digit number between 0-9
objRegEx.Pattern = "(\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b)"
strTrash = "00:87:90:65:67:98 192.165.32.23 192.165.32.25 vlan.10 none"
If objRegEx.Test(strTrash) Then
Set matchedIPs = objRegEx.Execute(strTrash)
End If
If matchedIPs.Count <> 0 Then
For i = 0 To matchedIPs.Count - 1
allIPs = allIPs & " " & matchedIPs.Item(i)
Next i
End If
MsgBox allIPs
End Sub