Reputation: 39
I am using the following Powershell code (modified version of https://gallery.technet.microsoft.com/scriptcenter/ea40c1ef-c856-434b-b8fb-ebd7a76e8d91) to parse an ini file:
$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 files that I deal with can contain keys that have an equal sign, and some that do not. For example:
[Cipher]
OpenSSL
[SSL]
CertFile=file.crt
The switch statement correctly matches the CertFile=file.crt
line and I was hoping that the last "([A-Z])\w+\s+"
condition would catch the OpenSSL
line. However it does not, and I have not been able to figure out what regex I can use to catch those lines where the key does not contain an equal sign.
Upvotes: 1
Views: 655
Reputation: 1761
The problem is that you're trying to match at least one whitespace character with \s+
You could use part of the regex you already have for matching the lines with =
.
"(.+?)\s*"
Consider anchoring your strings too in order the match the full line so it becomes
"^(.+?)\s*$"
Upvotes: 1