我有一個 PS 組態檔,我想與其他一些用戶共享,理想情況下,它會在加載時自動將它們發送到他們的主目錄。但是,我注意到用戶喜歡更改 home 變數的名稱以適合他們的喜好(足夠了)。
因此,我在 Profile 的末尾添加了一個 RegEx 模式,該模式選擇此組態檔行并提取為該變數定義的路徑,而不考慮變數名稱。它看起來像這樣:
$profileHome = gc $PSCommandPath
If ($profileHome[7] -notMatch '\s*# *\$' -and $profileHome[7] -match '\$\w \s*=\s*['"]?[A-Z]:[\\/]\w ' ) {...}
這樣我就可以強行將它們發送到他們的目錄,無論變數名稱如何,如果該變數設定為合理的路徑。
不幸的是,我已經在命令列上測驗了 RegEx,除了 ['"] 模式之外,一切正常,我似乎無法逃脫。
我知道這個類似的帖子,但不幸的是我無法得到它的解決方案。我嘗試了各種替代方案:
[`'"]
[\`'"]
[\[char\]0x27"]
[[char]0x27"]
還有一些看起來太傻而無法在此處輸入的其他變體。
這可以通過以下方式測驗:
PS>"`$home = 'C:/users'`r`ntest" > test.ps1
PS>$test = gc test.ps1
PS>If ($test[0] -match '\$\w \s*=\s*.?[A-Z]:[\\/]\w ' ) {echo 'hello'}
PS>hello
PS>If ($test[0] -match '\$\w \s*=\s*[`'"]?[A-Z]:[\\/]\w ' ) {echo 'hello'}
#This command is line wrapped into:
PS>If ($test[0] -match '\$\w \s*=\s*[`'
>> "]?[A-Z]:[\\/]\w ' ) {echo 'hello'}
在上面的成功回聲中,我將 ' 替換為 . 接受任何字符。在第二次嘗試中,我將 ' 留在了里面,但我無法逃脫它。經過一些測驗,我注意到可以通過將陳述句括在雙引號 " " 中并使用 ['`"] 來實作,顯然 `" 已正確轉義。這是一個合理的解決方法,但我仍然很好奇它是否是唯一的方法。
問題:是否無法轉義包含在 ' ' 中的 RegEx 的 ' 字符?
PS(5.1.19041)
uj5u.com熱心網友回復:
'在正則運算式中參考和使用字串的一些示例:
# All of these should match and return True
$single_quote = "'"
$single_quote -match "'" # using double quote
$single_quote -match '''' # doubling single quote
$single_quote -match @"
'
"@ # double-quoted here-string
$single_quote -match @'
'
'@ # single-quoted here-string
$single_quote -match '\x27' # using character code
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366191.html
標籤:电源外壳 powershell-5.0 powershell-5.1
