Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 to parse the paths:

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

$data.BaseName
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading