我使用以下Powershell代码(https://gallery.technet.microsoft.com/scriptcenter/ea40c1ef-c856-434b-b8fb-ebd7a76e8d91的修改版本)来解析ini文件:
$ini = @{}
$lastSection = ""
switch -regex -file $FilePath
{
"^\[(.+)\]$" # Section
{
$section = $matches[1]
$ini[$section] = @{}
$CommentCount = 0
$lastSection = $section
Continue
}
"^(;.*)$" # Comment
{
$section = "Comments"
if ($ini[$section] -eq $null)
{
$ini[$section] = @{}
}
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
$section = $lastSection
Continue
}
"(.+?)\s*=\s*(.*)" # Key
{
if (!($section))
{
$section = "No-Section"
$ini[$section] = @{}
}
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
Continue
}
"([A-Z])\w+\s+" # Key
{
if (!($section))
{
$section = "No-Section"
$ini[$section] = @{}
}
$value = $matches[1]
$ini[$section][$value] = $value
}
}
我处理的Ini文件可以包含具有相同符号的键,而有些则不包含。例如:
[Cipher]
OpenSSL
[SSL]
CertFile=file.crt
switch语句正确匹配CertFile=file.crt
行,我希望最后"([A-Z])\w+\s+"
条件能够捕获OpenSSL
行。但事实并非如此,而且我无法弄清楚我可以使用什么正则表达式来捕获那些键不包含等号的行。
答案 0 :(得分:1)
问题在于您尝试将至少一个空格字符与\s+
匹配
您可以使用已有的部分正则表达式来匹配=
行。
"(.+?)\s*"
考虑锚定你的字符串,以便匹配整行 它变成
"^(.+?)\s*$"