在 PowerShell 的替换运算符中使用格式运算符
Using Format Operator within Replace Operator in PowerShell
我正在尝试将我的文件 "Introduction _ C# _ Tutorial 1"
重命名为类似 "01.Introduction"
的名称。它需要一个 -replace
运算符以及一个 -f
运算符来零填充索引号。我的代码是这样的:
$string = "Introduction _ C# _ Tutorial 1"
if ($string -match "^([^_]+)_[^\d]+(\d{1,2})$") {
$Matches[0] -replace "^([^_]+) _[^\d]+(\d{1,2})$", ("{0:d2}. {1}" -f '', '')
}
然而,输出就像缺少 -f
运算符:
1. Introduction
我怎样才能得到预期的结果?
顺便说一下,有没有一种简单的方法可以得到 $matches
结果而不需要前面有 -match
语句,或者将 -match
语句组合成一行代码?
-match 已经填充了自动变量 $Matches,
> $Matches
Name Value
---- -----
2 1
1 Introduction
0 Introduction _ C# _ Tutorial 1
因此根本不需要 -replace 并重复 RegEx。
但您需要将数字转换为整数。
$string = "Introduction _ C# _ Tutorial 1"
if ($string -match "^([^_]+)_[^\d]+(\d{1,2})$") {
"{0:D2}. {1}" -f [int]$matches[2],$matches[1]
}
示例输出:
01. Introduction
我正在尝试将我的文件 "Introduction _ C# _ Tutorial 1"
重命名为类似 "01.Introduction"
的名称。它需要一个 -replace
运算符以及一个 -f
运算符来零填充索引号。我的代码是这样的:
$string = "Introduction _ C# _ Tutorial 1"
if ($string -match "^([^_]+)_[^\d]+(\d{1,2})$") {
$Matches[0] -replace "^([^_]+) _[^\d]+(\d{1,2})$", ("{0:d2}. {1}" -f '', '')
}
然而,输出就像缺少 -f
运算符:
1. Introduction
我怎样才能得到预期的结果?
顺便说一下,有没有一种简单的方法可以得到 $matches
结果而不需要前面有 -match
语句,或者将 -match
语句组合成一行代码?
-match 已经填充了自动变量 $Matches,
> $Matches
Name Value
---- -----
2 1
1 Introduction
0 Introduction _ C# _ Tutorial 1
因此根本不需要 -replace 并重复 RegEx。
但您需要将数字转换为整数。
$string = "Introduction _ C# _ Tutorial 1"
if ($string -match "^([^_]+)_[^\d]+(\d{1,2})$") {
"{0:D2}. {1}" -f [int]$matches[2],$matches[1]
}
示例输出:
01. Introduction