powershellwindows-10powershell-v5.1

Leftpad doesn't work when using with regex in Powershell


Here are two code blocks which show the strange behavior that Leftpad does.

$array = "z", "fg"
$array -replace "(\w{1,2})", '$1'.PadLeft(2, "0")
# output: z, fg

$array = "z", "fg"
$array -replace "(\w{1,2})", '$1'.PadLeft(3, "0")
# output: 0z, 0fg

How comes the pad length not fixed?

EDIT: @LotPings

I ask this another question is because of your way of doing it when applied to rename-item statement will not affect files with brackets in its names.

$file_names = ls "G:\Donwloads\Srt Downloads\15" -Filter *.txt
# the files are: "Data Types _ C# _ Tutorial 5.txt", "If Statements (con't) _ C# _ Tutorial 15.txt"
$file_names | 
    ForEach{
        if ($_.basename -match '^([^_]+)_[^\d]+(\d{1,2})$')
            { 
            $file_names | 
                Rename-Item -NewName `
                    { ($_.BaseName -replace $matches[0], ("{0:D2}. {1}" -f [int]$matches[2],$matches[1])) + $_.Extension }
            } 
           }

# output: 05. Data Types.txt
#         If Statements (con't) _ C# _ Tutorial 15.txt

As for the .PadLeft, I thought that the regex replacement group is of string type, it should work with .PadLeft but it doesn't.


Solution

  • Ansgars comment to your last question should have shown that your assumption on the order of actions was wrong.
    And Lee_Dailey proved you wrong another time.

    My answer to your previous question presented an alternative which also works here:

    ("Data Types _ C# _ Tutorial 5", "If Statements (con't) _ C# _ Tutorial 15") |
      ForEach{ 
        if ($_ -match '^([^_]+)_[^\d]+(\d{1,2})$'){
          "{0:D2}. {1}" -f [int]$matches[2],$matches[1]
        } 
      }
    

    Sample output:

    05. Data Types
    15. If Statements (con't)
    

    The last edit to your question is in fact a new question...


    $file_names = Get-ChildItem "G:\Donwloads\Srt Downloads\15" -Filter *.txt
    
    $file_names | Where-Object BaseName -match '^([^_]+)_[^\d]+(\d{1,2})$' |
        Rename-Item -NewName {"{0:D2}. {1}{2}" -f [int]$matches[2],$matches[1].Trim(),$_.Extension} -WhatIf