问题
I'm trying to rename my files "Introduction _ C# _ Tutorial 1"
to something like "01.Introduction"
. It needs a -replace
operator as well as a -f
operator to zero pad the index number. My code is like:
$string = "Introduction _ C# _ Tutorial 1"
if ($string -match "^([^_]+)_[^\d]+(\d{1,2})$") {
$Matches[0] -replace "^([^_]+) _[^\d]+(\d{1,2})$", ("{0:d2}. {1}" -f '$2', '$1')
}
The output, however, is like the -f
operator being absent:1. Introduction
How can I get the expected result?
By the way, is there a simple way to get the $matches
result without a -match
statement before it or combine the -match
statement to a one-liner code?
回答1:
The -match already fills the automatic variable $Matches,
> $Matches
Name Value
---- -----
2 1
1 Introduction
0 Introduction _ C# _ Tutorial 1
so there is no need for the -replace at all and repeat the RegEx.
But you need to cast the number to an int.
$string = "Introduction _ C# _ Tutorial 1"
if ($string -match "^([^_]+)_[^\d]+(\d{1,2})$") {
"{0:D2}. {1}" -f [int]$matches[2],$matches[1]
}
Sample output:
01. Introduction
来源:https://stackoverflow.com/questions/53976992/using-format-operator-within-replace-operator-in-powershell