在 PowerShell 的替换运算符中使用格式运算符 [英] Using Format Operator within Replace Operator in PowerShell
问题描述
我正在尝试将我的文件 "Introduction _ C# _ Tutorial 1"
重命名为类似 "01.Introduction"
的名称.它需要一个 -replace
运算符以及一个 -f
运算符来填充索引号.我的代码是这样的:
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')
}
然而,输出就像缺少 -f
运算符:
<代码>1.简介
我怎样才能得到预期的结果?
The output, however, is like the -f
operator being absent:
1. Introduction
How can I get the expected result?
顺便说一句,有没有一种简单的方法来获得 $matches
结果,而无需在 -match
语句之前加上 -match
语句或组合 -match
> 对单行代码的声明?
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?
推荐答案
-match 已经填充自动变量 $Matches,
The -match already fills the automatic variable $Matches,
> $Matches
Name Value
---- -----
2 1
1 Introduction
0 Introduction _ C# _ Tutorial 1
所以根本不需要 -replace 并重复 RegEx.
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]
}
示例输出:
01. Introduction
这篇关于在 PowerShell 的替换运算符中使用格式运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!