使用部分变量作为正则表达式字符串的一部分

using a partial variable as part of regular expression string

我正在尝试遍历一组警报代码并使用正则表达式在 cpp 代码中查找它。我知道我的正则表达式在我硬编码一个值并为我的正则表达式使用双引号时起作用,但我需要传入一个变量,因为它是一个大约 100 的列表,可以使用单独的定义进行查找。以下是我一般要使用的内容。我如何修复它以便它与 $lookupItem 一起工作,而不是在 Get-EpxAlarm 函数中使用硬编码“OTHER-ERROR”?我在 $fullregex 定义中尝试用单引号和双引号括起 $lookupItem,但 return 什么都没有。

Function Get-EpxAlarm{
  [cmdletbinding()]
  Param ( [string]$fileContentsToParse, [string]$lookupItem)
  Process
  {
     $lookupItem = "OTHER_ERROR"
     Write-Host "In epx Alarm" -ForegroundColor Cyan

     # construct regex
     $fullregex = [regex]'$lookupItem', # Start of error message########variable needed
     ":[\s\Sa-zA-Z]*?=",             # match anything, non-greedy
     "(?<epxAlarm>[\sa-zA-Z_0-9]*)", # Capture epxAlarm Num
     '' -join ''
    
     # run the regex
     $Values = $fileContentsToParse | Select-String -Pattern $fullregex -AllMatches

     # Convert Name-Value pairs to object properties
     $result = $Values.Matches
     Write-Host $result

     #Write-Host "result:" $result -ForegroundColor Green

     return $result
  }#process
}#function


#main code

    ...
    Get-EpxAlarm -fileContentsToParse $epxContents -lookupItem $item
    ...

$fileContentsToParse 在哪里

        case OTHER_ERROR:
            bstrEpxErrorNum = FATAL_ERROR;
            break;

        case RI_FAILED:
        case FILE_FAILED:
        case COMMUNICATION_FAILURE:
            bstrEpxErrorNum = RENDERING_ERROR;
            break;

因此,如果我查找 OTHER_ERROR,它应该 return FATAL_ERROR。

我在 regex editor 中测试了我的正则表达式,它适用于硬编码值。我如何定义我的正则表达式以便我使用参数,它 return 与对参数值进行硬编码相同?

我不建议尝试构建单个正则表达式来进行复杂的源代码解析 - 它很快就会变得非常不可读。

相反,编写一个小型错误映射解析器,逐行读取源代码并构建错误映射 table:

function Get-EpxErrorMapping {
  param([string]$EPXFileContents)

  # create hashtable to hold the final mappings
  $errorMap = @{}
  # create array to collect keys that are grouped together
  $keys = @()

  switch -Regex ($EPXFileContents -split '\r?\n') {
    'case (\w+):' {
        # add relevant key to key collection
        $keys += $Matches[1] }
    'bstrEpxErrorNum = (\w+);' {
        # we've reached the relevant error, set it for all relevant keys
        foreach($key in $keys){
            $errorMap[$key] = $Matches[1]
        }
    }
    'break' {
        # reset/clear key collection
        $keys = @()
    }    
  }

  return $errorMap
}

现在您需要做的就是调用此函数并使用生成的 table 来解析 $lookupItem 值:

Function Get-EpxAlarm{
  [CmdletBinding()]
  param(
    [string]$fileContentsToParse,
    [string]$lookupItem
  )

  $errorMap = Get-EpxErrorMapping $fileContentsToParse

  return $errorMap[$lookupItem]
}

现在我们可以得到对应的错误码:

$epxContents = @'
case OTHER_ERROR:
    bstrEpxErrorNum = FATAL_ERROR;
    break;

case RI_FAILED:
case FILE_FAILED:
case COMMUNICATION_FAILURE:
    bstrEpxErrorNum = RENDERING_ERROR;
    break;
'@

# this will now return the string "FATAL_ERROR"
Get-EpxAlarm -fileContentsToParse $epxContents -lookupItem OTHER_ERROR