INI 文件 - 在 VBS 中通过键名检索节名

INI file - retrieve a section name by key name in VBS

我想从只有唯一键名的 INI 文件中检索节名

我的 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]???

谢谢

我有两种方法可以找到所需的区号:

方法一

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

方法二(使用正则表达式)

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<<<

正则表达式解释:

  • \[ - 匹配文字 [
  • ([^]]+) - 在组
  • 中捕获 1+ 次不属于 ] 的任何字符
  • ] - 匹配文字 ]
  • \s* - 匹配 0+ white-spaces(包括换行符)
  • Title= - 匹配文本 Title=。然后将其与包含唯一标题值的变量 strKey 连接。