我需要通過 Powershell 將帶有多個單詞的輸入字串轉換為字串陣列。單詞可以由多個空格和/或換行符分隔。每個單詞都可以用單引號或雙引號轉義。有些詞可能以主題標簽開頭 - 在這種情況下,任何參考都會出現在該主題標簽之后。
這是一個可能的輸入和預期結果的代碼示例:
$inputString = @"
test1
#custom1
#"custom2" #'custom3'
#"custom ""four""" #'custom ''five'''
test2 "test3" 'test4'
"@
$result = @(
'test1'
'#custom1'
'"#custom2"'
"#'custom3'"
'#"custom ""four"""'
"#'custom ''five'''"
'test2'
'"test3"'
"'test4'"
)
是否有任何解決方案可以通過巧妙的 RegEx 運算式來做到這一點?或者有人有一個決議器片段/函式可以開始嗎?
uj5u.com熱心網友回復:
假設您完全控制或隱式信任輸入字串,您可以使用以下方法,該方法依賴于Invoke-Expression,通常應避免使用:
做出的假設:
#只出現在嵌入字串的開頭。- 沒有嵌入的字串本身包含換行符。
$inputString = @"
test1
#custom1
#"custom2" #'custom3'
#"custom ""four""" #'custom ''five'''
test2 "test3" 'test4'
"@
$embeddedStrings = Invoke-Expression @"
Write-Output $($inputString -replace '\r?\n', ' ' -replace '#', '`#')
"@
警告:本外引述周圍的各個串被丟在程序和嵌入式,躲過引號是轉義; 輸出$embeddedString收益率:
test1
#custom1
#custom2
#custom3
#custom "four"
#custom 'five'
test2
test3
test4
該方法依賴于您嵌入的字串使用 PowerShell 的參考和參考轉義規則這一事實;唯一的問題是前導#字符,它們`#如上所述被轉義。通過用\r?\n空格替換嵌入的換行符 ( ),結果可以作為位置引數的串列傳遞給Write-Output,在一個字串中,然后用 求值Invoke-Expression,這使得Write-Output輸出決議的引數一個一個,在變數中捕獲為陣列$embeddedStrings。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342530.html
上一篇:在r中決議多級json檔案
