Using Format Operator within Replace Operator in PowerShell [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-25 01:36:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!