简体   繁体   中英

How to append a number to a RegEx region variable in PowerShell?

I have JPEG files in a folder named sequentially: table1.jpg, table2.jpg, table3.jpg, ..., table11.jpg

I need to do some processing on them, in sequential order, but a Get-ChildItem will return this (even with Sort ):

table1.jpg
table10.jpg
table11.jpg
table2.jpg
table3.jpg
...

I would like to add a 0 to get them in the correct order:

table01.jpg
table02.jpg
table03.jpg
...
table11.jpg

I tried using RegEx with this command to preview the new names:

Get-ChildItem | % { $_.Name -replace "(.*[^0-9])([0-9]{1}\.jpg)",'$10$2' }

The idea is to get the first part of the name without any digit in first region, and one digit plus the extension in the second region. This will exclude files with two digits. And then I can replace by: first region + 0 + second region.

My problem is the "0" is seen as $10 instead of $1+"0", I don't know how to say it.

What would be the correct syntax? I tried "$10$2", "$1\\0$2", "$1`0$2", '$1"0"$2'

您可以使用命名组:

$filename -replace "(?<first>.*[^0-9])(?<second>[0-9]{1}\.jpg)", '${first}0${second}'
'"$1"0$2'

这应该做。

The correct syntax for indicating a numbered backreference without ambiguity is ${1} .

Here's a corrected version of your statement:

Get-ChildItem | % { $_.Name -replace "(.*\D)(\d\.jpg)",'${1}0$2' }

Note: I also used \\D , which is the built-in character class for [^0-9] , and \\d in place of [0-9] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM