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

僤鯓⒐⒋嵵緔 提交于 2020-01-02 10:06:18

问题


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.


来源:https://stackoverflow.com/questions/46360950/ini-file-retrieve-a-section-name-by-key-name-in-vbs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!