2017-09-22 134 views
2

檢索部分名字,我想從一個INI文件只有一個唯一的密鑰名稱檢索段名INI文件 - 由密鑰名在VBS

我的ini文件:

... 
[Area.104] 
Title=Central North America 
Local=Scenery\NAMC 
Layer=104 
Active=TRUE 
Required=FALSE 

[Area.105] 
Title=Eastern North America 
Local=Scenery\NAME 
Layer=105 
Active=TRUE 
Required=FALSE 

[Area.106] 
Title=Western North America 
Local=Scenery\NAMW 
Layer=106 
Active=TRUE 
Required=FALSE 
... 

哪有我從獨特的關鍵字Title = Eastern North America獲得部分名稱[Area.105]?

謝謝

回答

1

我找到所需的區號的方法有兩種:

方法1

Option Explicit 
Dim strFilePath, ofso, ofile, strFileData, strKey, strPrev, strCurr 
strFilePath=""  '<-- Enter the absolute path of your .ini file in this variable 

Set ofso = CreateObject("scripting.FileSystemObject") 
Set ofile = ofso.OpenTextFile(strFilePath,1,False) 
strKey = "Eastern North America"    '<-- Enter Unique title for which you want the Area code 

strPrev="" 
strCurr="" 
Do 
    strCurr = ofile.ReadLine 
    If InStr(1,strCurr,strKey)<>0 Then 
     Exit Do 
    End If 
    strPrev = strCurr 
Loop Until ofile.AtEndOfStream 
MsgBox strPrev 

Set ofile = Nothing 
Set ofso = Nothing 

方法2(使用正則表達式)

Option Explicit 
Dim strFilePath, ofso, ofile, strFileData, strKey, re, objMatches 
strFilePath=""   '<-- Enter the absolute path of your .ini file in this variable 

Set ofso = CreateObject("scripting.FileSystemObject") 
Set ofile = ofso.OpenTextFile(strFilePath,1,False) 
strFileData = ofile.ReadAll() 
ofile.Close 
strKey = "Eastern North America"  '<-- Enter Unique title for which you want the Area code 

Set re = New RegExp 
re.Global=True 
re.Pattern="\[([^]]+)]\s*Title="&strKey 
Set objMatches = re.Execute(strFileData) 
If objMatches.Count>0 Then 
    MsgBox objMatches.Item(0).Submatches.Item(0) 
End If 

Set re = Nothing 
Set ofile = Nothing 
Set ofso = Nothing 

>>>Click here for Regex Demo<<<

Regex的說明:

  • \[ - 匹配字面[
  • ([^]]+) - 這是不是一個組
  • ]]任何字符的捕獲1+發生 - 匹配字面]
  • \s* - ma tches 0+白色空格(包括換行符)
  • Title= - 與文本Title=相匹配。然後將其與包含唯一標題值的變量strKey連接。
+0

非常感謝Gurman,但是我怎樣才能用ADODB.Stream而不是scripting.FileSystemObject的腳本與_autodetect_all的字符集?實際上我的ini文件可以用不同的字符集編碼; –

+0

默認情況下,'opentextfile'方法以ASCII格式打開文本文件。要以UNICODE格式打開它,請使用以下代碼行:'Set ofile = ofso.OpenTextFile(strFilePath,1,False,1)'。更多的幫助在這裏:https://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx – Gurman

+0

感謝但不幸的是,當ini文件編碼爲UTF-16LE它不適用於您方法 –