INI file - retrieve a section name by key name in

2019-05-29 20:02发布

问题:

I would like to retrieve a section name from an INI file with only a unique key name

My ini file :

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

How can I get section name [Area.105] from unique key Title=Eastern North America ???

Thank you

回答1:

I have two ways of finding the required Area code:

METHOD 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

METHOD 2(Using Regular Expression)

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

  • \[ - matches literal [
  • ([^]]+) - capture 1+ occurrence of any character which is not ] in a group
  • ] - matches literal ]
  • \s* - matches 0+ white-spaces(which include the newline characters)
  • Title= - matches the text Title=. This is then concatenated with the variable strKey containing the value of unique title.


标签: vbscript ini