INI文件 - 由密钥名在VBS
问题描述:
检索部分名字,我想从一个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
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它不适用于您方法 –