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.