Powershell 正则表达式组:如何获取所有子组 2

Powershell regex group : how do I get all subgroups 2

我想提取 file1、file2 我知道如何在 javascript 中执行此操作,我在 Powershell 中迷路了,我只能提取 tut https://devblogs.microsoft.com/scripting/regular-expressions-regex-grouping-regex/ 之后的整个第二个匹配项,这是什么语法 ?

  $regex = '(.+\)*(.+)\.(.+)$'
  $data = @'
  "C:\test\file1.txt"
  "C:\test\file2.txt"
  '@
  [RegEx]::Matches($data,$regex).value

下面是调用 Regex.Matches:

的方法
$data = @'
"C:\test\file1.txt"
"C:\test\file2.txt"
'@

$regex = [regex] '(.+\)*(?<base>.+)\.(.+)'
$regex.Matches($data).ForEach{ $_.Groups['base'] }.Value

# Results in:
# file1
# file2

但是,由于您要处理路径,我个人建议您使用 FileInfo class to parse them. In this example, we can use the String .Trim(Char) Method to remove the leading and trailing " from each path and the -as Type Operator 将字符串安全地转换为 System.IO.FileInfo 个实例。

$data = (@'
"C:\test\file1.txt"
"C:\test\file2.txt"
'@ -split '\r?\n').Trim('"') -as [IO.FileInfo[]]

$data.BaseName

使用 -match$matches 自动变量检索捕获组值的示例:

$data = @'
"C:\test\file1.txt"
"C:\test\file2.txt"
'@

$data -match '\([^.\]+)\.[\s\S]+?\([^.\]+)\.'

write-host $matches[1]    # file1
write-host $matches[2]    # file2

为了完整起见,另一个 RegEx 解决方案:

$data = @'
"C:\te.st\file1.txt"
"C:/test/file2.foo.txt"
'@

[regex]::Matches($data, '[^\/]+(?=\.[^\/]+\")').Value

输出:

file1
file2.foo

RegEx 使用 positive lookahead (?=) 断言后跟一个扩展,而不捕获它。

详细说明在 regex101

我仍然认为 更健壮且更易于维护。与简单地拆分和转换为 FileInfo 相比,我花费了更长的时间来获得正确的 RegEx。