【问题标题】:INI file - retrieve a section name by key name in VBSINI 文件 - 在 VBS 中通过键名检索节名
【发布时间】:2017-09-22 09:09:04
【问题描述】:

我想从一个只有唯一键名的 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] ???

谢谢

【问题讨论】:

    标签: vbscript ini


    【解决方案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<<<

    正则表达式解释:

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

    【讨论】:

    • 非常感谢 Gurman,但是我怎样才能将您的脚本与 ADODB.Stream 一起使用,而不是使用带有 Charset 到 _autodetect_all 的 scripting.FileSystemObject 呢?其实我的ini文件可以用不同的字符集编码;
    • 默认情况下,opentextfile 方法以 ASCII 格式打开文本文件。要以 UNICODE 格式打开它,请使用以下行:Set ofile = ofso.OpenTextFile(strFilePath,1,False,1)。更多帮助:msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx
    • 谢谢,但不幸的是,当 ini 文件被编码为 UTF-16LE 时,它不适用于您的方法
    • 如果我找到解决方案,我会回复您。同时你可以取消选择这个作为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2016-09-18
    • 2011-01-10
    • 1970-01-01
    • 2021-07-17
    • 2011-05-14
    • 2015-02-17
    相关资源
    最近更新 更多