1

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?

preachers
  • 373
  • 1
  • 5
  • 15
  • 2
    Your approach doesn't work because `"{0:d2}. {1}" -f '$2', '$1'` takes place *before* the regular expression replacement. Since `$1` is a string, formatting it with double digits doesn't do anything, so you end up with a replacement string `'$2. $1'`. – Ansgar Wiechers Dec 30 '18 at 11:29
  • @Ansgar Wiechers Without the parathesis around the `"{0:d2}. {1}" -f '$2', '$1'` part, the formatting still doesn't work. What else can I do to get the expected result from this `-replace` syntax? – preachers Dec 30 '18 at 12:07
  • @preachers Please read the answers to the question linked at the top of your question. – Ansgar Wiechers Dec 30 '18 at 12:58

1 Answers1

2

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