[英]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.