我正在研究一個獲取字串鍵映射的函式,它是十六進制值。我得到了字串鍵部分的作業,但我無法讓十六進制部分作業。到目前為止,這是我的功能:
function Get-Contents4_h{
[cmdletbinding()]
Param ([string]$fileContent)
#define Error_Failed_To_Do_A 0x81A0 /* random comments */
#define Error_Failed_To_Do_B 0x810A
# create an ordered hashtable to store the results
$errorMap = [ordered]@{}
# process the lines one-by-one
switch -Regex ($fileContent -split '\r?\n') {
'define ([\w]*)' { # Error_Failed_To_Do_ #this works fine
$key = ($matches[1]).Trim()
}
'([0x\w]*)' { # 0x04A etc #this does not work
$errorMap[$key] = ($matches[1]).Trim()
}
}
# output the completed data as object
#[PsCustomObject]$errorMap
return $errorMap
}
我將遍歷回傳的映射并將十六進制值與另一個物件中的鍵匹配。
這是函式的字串引數的樣子:
#define Error_Failed_To_Do_A 0x81A0 /* random comments */
#define Error_Failed_To_Do_B 0x810A
出于某種原因我的
0x\w
regex 未在 regex101.com 中回傳任何內容。我對其他十六進制數字很幸運,但這次不是。
我也嘗試過這個和其他變體:^[\s\S]*?#[\w]*[\s\S] ([0x\w]*)
這適用于 powershell 5.1 和 VS Code。
uj5u.com熱心網友回復:
您需要洗掉[...]范圍構造0x\w-0x在輸入字串中僅出現一次,并且以下字符至少出現一次 - 但運算式[0x\w]*可以由空字串滿足(感謝*, 0 或更多量詞)。
我建議用一個模式一次匹配整行:
switch -Regex ($fileContent -split '\r?\n') {
'^\s*#define\s (\w )\s (0x\w )' {
$key,$value = $Matches[1,2] |ForEach-Object Trim
$errorMap[$key] = $value
}
}
uj5u.com熱心網友回復:
這對我有用。方括號一次匹配其中的任何一個字符。帶有方括號的模式在這一行中有 18 個匹配項,第一個匹配項是空字串 ''。Regex101.com 說了同樣的話(null)。 https://regex101.com/r/PZ8Y8C/1 這會起作用0x[\w]*,但你不妨去掉括號。我制作了一個示例資料檔案,然后制作了一個關于如何操作的腳本。
'#define Error_Failed_To_Do_A 0x81A0 /* random comments */' |
select-string [0x\w]* -AllMatches | % matches | measure | % count
18
'#define Error_Failed_To_Do_A 0x81A0 /* random comments */
#define Error_Failed_To_Do_B 0x810A' |
set-content file.txt
# Get-Contents4_h.ps1
Param ($file)
switch -Regex -File $file {
'define (\w ).*(0x\w )' {
[pscustomobject]@{
Error = $matches[1]
Hex = $matches[2]
}
}
}
.\Get-Contents4_h file.txt
Error Hex
----- ---
Error_Failed_To_Do_A 0x81A0
Error_Failed_To_Do_B 0x810A
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453904.html
