Regular expression for converting file string in PowerShell Regular expression for converting file string in PowerShell powershell powershell

Regular expression for converting file string in PowerShell


You could do a single -replace operation:

$FileName -replace '^\D+([\.\d]+)\srev\.\s(\d+)','$1.$2'

Breakdown:

^\D+       # 1 or more non-digits - matches ie. "Some nameA "  ([\.\d]+)  # 1 or more dots or digits, capture group - matches the version  \srev\.\s  # 1 whitespace, the characters r, e and v, a dot and another whitespace  (\d+)      # 1 or more digits, capture group - matches the revision number

In the second argument, we refer to the two capture groups with $1 and $2

You can pipe Get-ChildItem to ForEach-Object instead of using a for loop and indexing into $files:

Get-ChildItem . *.zip |ForEach-Object {    $_.BaseName -replace '^\D+([\.\d]+)\srev\.\s(\d+)','$1.$2'} | Out-File output.txt