2012-03-30 117 views
0

我有一個文本文件,包含區域轉移的結果&需要讀取每一行&將其拆分成數組以輸出服務器名稱列表& IP地址。不過,我在分割數據時遇到了一些問題,因爲我對空格分隔符的嘗試似乎沒有按照我想要的那樣做。使用正則表達式分隔文本文件內容的分隔符?

樣品輸入:

machine1.fqdn.com. 86400 IN A 192.168.1.10 
machine2.fqdn.com. 86400 IN A 192.168.1.11 
machine3.fqdn.com. 86400 IN A 192.168.1.12 
machine4.fqdn.com. 86400 IN A 192.168.1.13 

腳本:

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objFile = objFSO.OpenTextFile("I:\testHarvestIF.txt", ForReading) 

Const ForReading = 1 

Do Until objFile.AtEndOfStream 
strNextLine = objFile.Readline 
arrServiceList = Split(strNextLine," ",-1,1) 
Wscript.Echo "Server name: " & arrServiceList(0) & vbCrLF & _ 
    " - IP Address: " & arrServiceList(2) 
Loop 

objFile.Close 

電流輸出:

Server name: machine1.fqdn.com. 
IP Address: IN A 192.168.1.10 
Server name: machine2.fqdn.com. 
IP Address: IN A 192.168.1.11 
Server name: machine3.fqdn.com. 
IP Address: IN A 192.168.1.12 
Server name: machine4.fqdn.com. 
IP Address: IN A 192.168.1.13 

希望的輸出:

Server name: machine1.fqdn.com. 
IP Address: 192.168.1.10 
Server name: machine2.fqdn.com. 
IP Address: 192.168.1.11 
Server name: machine3.fqdn.com. 
IP Address: 192.168.1.12 
Server name: machine4.fqdn.com. 
IP Address: 192.168.1.13 

有什麼方法可以使用正則表達式來使用任意長度的空白作爲分隔符?例如。

arrServiceList = Split(strNextLine,"^\s+",-1,1) 

預先感謝您可以提供任何幫助。

問候,

RB

回答

-1

用RegExp對象(MSDN)所要求的字符串匹配,而不是劈裂的字符串:

set regex = new RegExp 
    regexp.pattern = "^.*? " 
    set serverName = regex.execute(inputText).value 
    regex.pattern = " .*?$" 
    set ipAddress = regex.execute(inputText).value 
+0

對於我之前的回答,我很抱歉。我看着它,結果vbscript不支持從Match對象中提取捕獲組。 (<-verify我) – Untitled 2012-03-30 12:48:50

+0

設置objFSO =的CreateObject( 「Scripting.FileSystemObject的」) 集OBJFILE = objFSO.OpenTextFile( 「I:\ test.txt的」,ForReading的) CONST ForReading的= 1 功能splitRE(strSource,圖案) 用的CreateObject( 「vbscript.regexp」) 。全球=真 .Pattern =模式 splitRE =斯普利特(.Replace(strSource, 「 」),「」) 尾隨着 端功能 做,直到OBJFILE。 AtEndOfStream strNextLine = objFile.Readline arrServiceList = splitRE(strNextLine,「\ s +」) Wscript.Echo「服務器名稱:」&arrServiceLis t(0)&「 - IP Address:」&arrServiceList(4) Loop objFile.Close – Pr0m3th3us 2012-03-30 13:25:36

0

這可能無法正常工作,這取決於格式您的數據,但可以嘗試在調用Split之前用單個空格字符替換多餘的空格:

Dim re : Set re = New RegExp 
re.Global = True 
re.Pattern = "\s+" 

Do Until objFile.AtEndOfStream 
strNextLine = re.Replace(objFile.Readline, " ") 
arrServiceList = Split(strNextLine," ",-1,1) 
Wscript.Echo "Server name: " & arrServiceList(0) & vbCrLF & _ 
    " - IP Address: " & arrServiceList(4) 
Loop