我用这个来查找文件名是否包含7位数字
if ($file.Name -match 'D(d{7})(?:D|$)') {
$result = $matches[1]
}
问题是当有一个文件名包含2组7位数字时例如:
patch-8.6.22 (1329214-1396826-Increase timeout.zip
在本例中,结果将是第一个(1329214)。对于大多数情况,只有一个数字,所以正则表达式是工作的,但我必须识别是否有多于一个组,并集成到if ()
-
-match
运算符只查找一个匹配。 -
要获得多个,当前必须直接使用底层的。net api,特别是
[regex]::Matches()
:- 注意:有一个绿灯提案来实现
-matchall
操作符,但截至PowerShell 7.3.0,它尚未实现-参见GitHub issue #7867。
- 注意:有一个绿灯提案来实现
# Sample input.
$file = [pscustomobject] @{ Name = 'patch-8.6.22 (1329214-1396826-Increase timeout.zip' }
# Note:
# * If *nothing* matches, $result will contain $null
# * If *one* substring matches, return will be a single string.
# * If *two or more* substrings match, return will be an *array* of strings.
$result = ([regex]::Matches($file.Name, '(?<=D)d{7}(?=D|$)')).Value
.Value
使用成员访问枚举从[regex]::Matches()
返回的集合元素中提取匹配的子字符串(如果有)。我已经调整了正则表达式来使用查找断言(
(?<=/...)
和(?=...)
),以便只捕获感兴趣的子字符串。- 请参阅regex101.com页面,了解正则表达式的解释以及使用它进行实验的能力。