Powershell 正则表达式缺少 CR 等

Powershell regex missing ones with CR etc

我正在使用正则表达式来提取键和关联字符串的映射。

出于某种原因,它适用于未显示线拆分但错过了线拆分的行。

这是我正在使用的:

  $errorMap = [ordered]@{}
  # process the lines one-by-one
  switch -Regex ($fileContent -split ';') {
    'InsertCodeInfo\(([\w]*), "(.*)"' { # key etc., followed by string like "Media size cassette missing"
      $key,$value = ($matches[1,2])|ForEach-Object Trim
      $errorMap[$key] = $value
    }
}

这是 $fileContent 的示例:

    InsertCodeInfo(pjlWarnCommunications, 
        "communications error");
    InsertCodeInfo(pjlNormalOnline, 
        "Online");
    InsertCodeInfo(pjlWarnOffline, 
        "offline");
    InsertCodeInfo(pjlNormalAccessing, "Accessing");  #this is first match :(
    InsertCodeInfo(pjlNormalArrive, "Normal arrive");
    InsertCodeInfo(pljNormalProcessing, "Processing");
    InsertCodeInfo(pjlNormalDataInBuffer, "Data in buffer");

它从 pjlNormalAccessing 向下返回对,其中没有行拆分。我认为使用分号分隔正则表达式内容可以解决问题,但没有帮助。我以前用

拆分正则表达式内容

'\r?\n'

我想 VSCode 可能出了什么问题,所以我退出并重新打开它,然后重新 运行 脚本得到了相同的结果。知道如何让它通过分号行与键值对匹配每个 InsertCodeInfo 吗?

这是使用 VSCode 和 Powershell 5.1。

更新:

有人问 $fileContent 是如何创建的:

我使用文件名路径($FileHandler)和 from/to strings/methodNames($matchFound2 稍后成为 $fileContent 作为方法参数)调用我的方法:

$matchFound2 = Get-MethodContents -codePath $FileHandler -methodNameToReturn "OkStatusHandler::PopulateCodeInfo" -followingMethodName "OkStatusHandler::InsertCodeInfo"

Function Get-MethodContents{
  [cmdletbinding()]
  Param ( [string]$codePath, [string]$methodNameToReturn, [string]$followingMethodName)
  Process
  {
      $contents = ""
      Write-Host "In GetMethodContents method File:$codePath method:$methodNameToReturn followingMethod:$followingMethodName"  -ForegroundColor Green

      $contents = Get-Content $codePath -Raw #raw gives content as single string instead of a list of strings

      $null = $contents -match  "($methodNameToReturn[\s\S]*)$followingMethodName" #| Out-Null  

      return $Matches.Item(1) 
  }#End of Process
}#End of Function

这个正则表达式似乎能捕获所有行,包括中间有换行符的行。感谢@WiktorStribizew 的建议。我调整了你的建议,很有帮助。

InsertCodeInfo\(([\w]*),[\s]*"([^"]*)

它可能是最简洁的,但它包罗万象。一如既往地欢迎 post 其他建议。这就是为什么我不接受我自己的回答。

您可以使用

InsertCodeInfo\((\w+),\s*"([^"]*)

参见online regex demo

详情:

  • InsertCodeInfo\( - 文字 InsertCodeInfo( 文本
  • (\w+) - 第 1 组:一个或多个单词字符(字母、数字、变音符号或下划线(连接符)
  • , - 逗号
  • \s* - 零个或多个空格
  • " - 一个 " 字符
  • ([^"]*) - 第 2 组:除 " 字符之外的零个或多个字符。

参见regex graph