PowerShell regex grouping PowerShell regex grouping powershell powershell

PowerShell regex grouping


Will this work for you:

Get-ChildItem | Foreach-Object {   if ($_.BaseName -match "(\d{4} - [^-]*)") {       echo $matches[0].TrimEnd()    }}

Note the TrimEnd - this is to trim the trailing space before the second dash.

As for why your examples do not work: \w+ matches any word character so it will not match the space inside "something interesting". * means zero or more. So -* matches zero or more dashes, in your case - zero.

Another way to write an expression that might work for you is:

Get-ChildItem | Foreach-Object {   if ($_.BaseName -match "(\d{4} - .+(?= -))") {       echo $matches[0]    }}

where the (?= -) construct is positive lookahead assertionIn this case you do not need to trim the extra space at the end as it is accounted for in the regular expression itself.

Update 1

Modified to do the transformation:

gci | %{ $_.BaseName -replace "(\d{4}) - (.+)(?= -).*" ,'$2 ($1)' }


Try this:

Get-ChildItem |     Select-String -Pattern '(\d{4})\s+-\s+(\w+(\s+\w+)*)\s+-.*' |    Foreach-Object { "$($_.Matches.Groups[2].Value) ($($_.Matches.Groups[1].Value))" }