我正在研究一個正則運算式來提取鍵和關聯字串的映射。
出于某種原因,它適用于不顯示分行但錯過有分行的行。
這就是我正在使用的:
$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 是如何創建的:
I call my method with the filenamepath ($FileHandler), and from/to strings/methodNames ($matchFound2 becomes $fileContent later as a method parameter):
$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
uj5u.com熱心網友回復:
您可以使用
InsertCodeInfo\((\w ),\s*"([^"]*)
請參閱
uj5u.com熱心網友回復:
這個正則運算式似乎捕獲了所有行,包括中間有換行符的行。感謝@WiktorStribizew 的建議。我調整了你的建議,它有幫助。
InsertCodeInfo\(([\w]*),[\s]*"([^"]*)
它可能是最簡潔的,但它抓住了所有的線條。隨時發布替代建議。這就是為什么我不接受自己的答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457117.html
標籤:regex powershell
