'Powershell regex group : how do I get all subgroups 2

I want to extract file1, file2 I know how to do this in javascript, I'm lost in Powershell, I can only extract the whole second match following that tut https://devblogs.microsoft.com/scripting/regular-expressions-regex-grouping-regex/, what's the syntax ?

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


Solution 1:[1]

Here is how you could do it using the call to 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

However since you're dealing with paths, I would personally recommend you to use 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 to safely convert the strings into System.IO.FileInfo instances.

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

$data.BaseName

Solution 2:[2]

Just for completeness another RegEx solution:

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

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

Output:

file1
file2.foo

The RegEx uses a positive lookahead (?=) to assert that an extension follows, without capturing it.

Detailed explanation at regex101.

I still think that the FileInfo solution is more robust and easier to maintain. It took me much longer to get the RegEx right than simply splitting and converting to FileInfo would have taken.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2