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

时间:2017-09-22 09:09:05

标签: vbscript ini

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

的节名

我的ini文件:

<% @cities.each do |c| %>
  # your code to show each city
  c
<% end %>

如何从唯一键Title = Eastern North America ???

获取章节名称[Area.105]

谢谢

1 个答案:

答案 0 :(得分:1)

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

方法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连接。