我正在嘗試遍歷一組警報代碼并使用正則運算式在 cpp 代碼中查找它。我知道當我對一個值進行硬編碼并為我的正則運算式使用雙引號時,我的正則運算式可以作業,但是我需要傳入一個變數,因為它是一個大約 100 個的串列,用于查找單獨的定義。以下是我一般想要使用的內容。如何修復它以便它與 $lookupItem 一起使用而不是硬編碼“OTHER-ERROR”,例如在 Get-EpxAlarm 函式中?我在 $fullregex 定義中圍繞 $lookupItem 嘗試了單引號和雙引號,但它什么都不回傳。
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,它應該回傳 FATAL_ERROR。
我在正則運算式編輯器中測驗了我的正則運算式,它適用于硬編碼值。如何定義我的正則運算式以便我使用引數并回傳與硬編碼引數值相同的內容?
uj5u.com熱心網友回復:
我不建議嘗試構建單個正則運算式來進行復雜的源代碼決議 - 它很快就會變得非常不可讀。
相反,撰寫一個小的錯誤映射決議器,它只是逐行讀取源代碼并隨著它的進行構建錯誤映射表:
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
}
現在你需要做的就是呼叫這個函式并使用結果表來決議$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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/384887.html
