INI文件-在VBS中按键名检索节名 [英] INI file - retrieve a section name by key name in VBS

查看:90
本文介绍了INI文件-在VBS中按键名检索节名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

谢谢

推荐答案

我有两种查找所需区号的方法:

I have two ways of finding the required Area code:

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

>>>单击此处以查看Regex演示<<<

正则表达式说明

  • \[-匹配文字[
  • ([^]]+)-捕获1+个出现在组中不是]的字符
  • ]-匹配文字]
  • \s*-匹配0+空格(包括换行符)
  • Title=-与文本Title=匹配.然后将其与包含唯一标题值的变量strKey串联.
  • \[ - 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.

这篇关于INI文件-在VBS中按键名检索节名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆