1

我正在尝试将我的文件重命名"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 '$2', '$1')
    }

然而,输出就像-f操作员缺席一样:
1. Introduction
我怎样才能得到预期的结果?

顺便说一句,有没有一种简单的方法可以在$matches没有语句的情况下获得结果-match,或者将-match语句组合成单行代码?

4

1 回答 1

2

-match 已经填充了自动变量 $Matches,

> $Matches

Name                           Value
----                           -----
2                              1
1                              Introduction
0                              Introduction _ C# _ Tutorial 1

所以根本不需要 -replace 并重复 RegEx。

但是您需要将数字转换为 int。

$string = "Introduction _ C# _ Tutorial 1"
if ($string -match "^([^_]+)_[^\d]+(\d{1,2})$") {
    "{0:D2}. {1}" -f [int]$matches[2],$matches[1]
}

样本输出:

01. Introduction
于 2018-12-30T11:26:36.720 回答