2017-09-22 18 views
2

にキー名でセクション名を取得INIファイル - 私は一意のキーの名前でINIファイルからセクション名を取得したいと思いVBS

私の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 
... 

どのようにすることができますユニークキータイトル=東北アメリカからセクション名[Area.105]を取得する???

は、私は必要な市外局番見つけるの二つの方法持って

答えて

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 

METHOD 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* - ma 0個以上の空白文字(改行文字を含む)
  • Title= - テキストTitle=と一致します。これは、一意のタイトルの値を含む変数strKeyと連結されます。
+0

ありがとうGurmanさん、ありがとうございます。でも、私はあなたのスクリプトをスクリプト化の代わりにADODB.Streamで使うことができます.FileSystemObjectをCharsetで_autodetect_allにするには?実際、私のiniファイルは、異なる文字コードでエンコードすることができます。 –

+0

デフォルトでは、 'opentextfile'メソッドはテキストファイルをASCII形式で開きます。 UNICODE形式で開くには、 'Set ofile = ofso.OpenTextFile(strFilePath、1、False、1)'という行を使います。その他のヘルプ:https://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx – Gurman

+0

残念ながら、iniファイルがUTF-16LEとしてエンコードされていると、あなたのメソッド –

関連する問題