我找到所需的區號的方法有兩種:
方法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
連接。
非常感謝Gurman,但是我怎樣才能用ADODB.Stream而不是scripting.FileSystemObject的腳本與_autodetect_all的字符集?實際上我的ini文件可以用不同的字符集編碼; –
默認情況下,'opentextfile'方法以ASCII格式打開文本文件。要以UNICODE格式打開它,請使用以下代碼行:'Set ofile = ofso.OpenTextFile(strFilePath,1,False,1)'。更多的幫助在這裏:https://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx – Gurman
感謝但不幸的是,當ini文件編碼爲UTF-16LE它不適用於您方法 –