如何匹配可能不包含等号的 ini 文件密钥?

How do I match ini file keys that may not contain an equal sign?

我正在使用以下 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 行。但是它没有,而且我无法弄清楚我可以使用什么正则表达式来捕捉那些键不包含等号的行。

问题是您试图将 至少一个空格 字符与 \s+

匹配

您可以使用已有的正则表达式的一部分来匹配 = 的行。

"(.+?)\s*"

也考虑锚定你的字符串,以便匹配整行 它变成

"^(.+?)\s*$"