代码之家  ›  专栏  ›  技术社区  ›  Erik Bender

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

  •  2
  • Erik Bender  · 技术社区  · 8 年前

    我想从仅具有唯一键名的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
    ...
    

    非常感谢。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Gurmanjot Singh    8 年前

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

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

    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*
    • Title= -与文本匹配 标题= . 然后将其与变量连接 strKey