[英]Get path based on regex Powershell
我查詢注冊表以獲取我正在尋找的文件路徑。 但是,我需要將 go 降低一個目錄來檢索我需要的一些文件信息。 我試圖匹配的模式是Officexx
或OFFICExx
。 我似乎無法找到我需要的路徑。
從注冊表中找到路徑: C:\Program Files\Microsoft Office
我需要的是: C:\Program Files\Microsoft Office\Officexx
代碼:
$base_install_path = "C:\Program Files\Microsoft Office";
$full_install_path = $base_install_path+'\Office[\d+.*]'
Write-Output $full_install_path;
這將返回:
C:\Program Files\Microsoft Office\Office[\d+.*]
所需的 output:
C:\Program Files\Microsoft Office\Office15
不是這可以是任何兩位數# ^^
基於Santiago Squarzon 的有用評論:
# Find all child directories matching the given wildcard pattern, if any.
Get-ChildItem -Directory -Path "$base_install_path\Office[0-9][0-9]*"
以上使用 PowerShell 通配符表達式來執行所需的匹配,精確匹配兩個數字( [0-9][0-9]
),后跟零個或多個字符( *
),無論它們是什么(可能包括額外的數字) .
鑒於通配符模式僅支持一個非特定的重復結構,即上述*
,匹配特定范圍的數字 - 例如最多1 或 2 或特定數字- 例如正好兩個- 需要基於 a 的后過濾正則表達式:
# Find all child directories matching the given regex, if any.
# Matches 'Office' at the start of the name (^),
# followed by 1 or 2 ({1,2}) digits (\d),
# followed by at least non-digit (\D), if any (?)
Get-ChildItem -Directory -LiteralPath $base_install_path |
Where-Object Name -match '^Office\d{1,2}\D?'
至於你嘗試了什么:
[\d+.*]
是一個正則表達式,但你可能的意思是\d.*
在字符范圍/集表達式 ( [...]
) 內, .
和*
逐字使用,即它們不是元字符並且匹配文字.
和*
字符。
Get-ChildItem -Path 'C:\Program Files\Microsoft Office\' -Directory |
Where-Object { $_.Name -match 'Office\d+' }
在您的正則表達式中, []
是一個字符 class ,這意味着[\d+.*]
不是“一個或多個數字”,而是“反斜杠 OR d OR plus OR dot OR asterisk”。
PS C:\> "d+\" -match "[\d+]"
True
不是你要找的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.