如何使用 RegEx 获取 Ini 文件中的部分名称
How to get a section Name in an Ini file using RegEx
我正在使用下面的正则表达式来提取 Ini 文件中某个部分的名称。
^\s*\[([a-z_][0-9])\]\s*
但即使在像
这样的简单行上,我也无法找到匹配项
[Compiler]
Path=C:\ProgramFiles (x86)\ProtonIDE\PDS
Database=C:\Program Files (x86)\ProtonIDE
我错过了什么?
模式中的这部分 [a-z_][0-9]
匹配 2 个字符,第一个字符是 a-z 或 _,第二个字符是数字。
您可以从中拼出 1 个字符 class,然后再重复 1 次以上。如果要匹配大写字符,可以使模式不区分大小写或向其添加 [A-Z]。
那你也可以缩短为\w
^\s*\[(\w+)\]
注意 \s
也匹配换行符。您还可以使用 \h*
来匹配 0+ 个水平空白字符。
您可以使用模式 '^\[\w+\]$'
来获取如下部分:
with TStringList.Create do
try
Add('[Compiler]');
Add('Path=C:\ProgramFiles (x86)\ProtonIDE\PDS');
Add('Database=C:\Program Files (x86)\ProtonIDE)');
with TPerlRegEx.Create do
try
Options:= [preMultiLine];
Subject:= Text;
RegEx:= '^\[\w+\]$';
while MatchAgain do
ShowMessage(MatchedText);
// or ShowMessage(MatchedText.Replace('[', '').Replace(']', '')); if you wish to
finally
Free;
end;
finally
Free;
end;
而最简单的方法是使用TMemIniFile
的ReadSections()方法
with TMemIniFile.Create('YourIniFile') do
try
ReadSections(Memo1.Lines);
finally
Free;
end;
我正在使用下面的正则表达式来提取 Ini 文件中某个部分的名称。
^\s*\[([a-z_][0-9])\]\s*
但即使在像
这样的简单行上,我也无法找到匹配项[Compiler]
Path=C:\ProgramFiles (x86)\ProtonIDE\PDS
Database=C:\Program Files (x86)\ProtonIDE
我错过了什么?
模式中的这部分 [a-z_][0-9]
匹配 2 个字符,第一个字符是 a-z 或 _,第二个字符是数字。
您可以从中拼出 1 个字符 class,然后再重复 1 次以上。如果要匹配大写字符,可以使模式不区分大小写或向其添加 [A-Z]。
那你也可以缩短为\w
^\s*\[(\w+)\]
注意 \s
也匹配换行符。您还可以使用 \h*
来匹配 0+ 个水平空白字符。
您可以使用模式 '^\[\w+\]$'
来获取如下部分:
with TStringList.Create do
try
Add('[Compiler]');
Add('Path=C:\ProgramFiles (x86)\ProtonIDE\PDS');
Add('Database=C:\Program Files (x86)\ProtonIDE)');
with TPerlRegEx.Create do
try
Options:= [preMultiLine];
Subject:= Text;
RegEx:= '^\[\w+\]$';
while MatchAgain do
ShowMessage(MatchedText);
// or ShowMessage(MatchedText.Replace('[', '').Replace(']', '')); if you wish to
finally
Free;
end;
finally
Free;
end;
而最简单的方法是使用TMemIniFile
with TMemIniFile.Create('YourIniFile') do
try
ReadSections(Memo1.Lines);
finally
Free;
end;