2017-06-20 22 views
1

我使用下面的PowerShell代码(的https://gallery.technet.microsoft.com/scriptcenter/ea40c1ef-c856-434b-b8fb-ebd7a76e8d91修改后的版本)来解析ini文件:如何匹配可能不包含等号的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线。然而,它并没有,我还没有能够找出什么正则表达式我可以用来捕捉密钥不包含等号的那些行。

回答

1

的问题是,你想匹配至少一个空白字符\s+

你可以使用你已经拥有的线与=匹配正则表达式的一部分。

"(.+?)\s*"

考虑锚固你的琴弦太为了比赛的全线所以 成为

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

+0

重用以前的正则表达式的第一部分加上锚('“^(。+?)\ S * $“')确实为我工作。我应该注意到,直到我添加了锚定,它才正常工作。没有锚定,'$ matches [1]'只是“O”,但是一旦我添加锚定,它就匹配完整的字符串。谢谢! –