【问题标题】:Using Format Operator within Replace Operator in PowerShell [duplicate]在PowerShell的替换运算符中使用格式运算符[重复]
【发布时间】:2018-12-30 10:46:36
【问题描述】:

我正在尝试将我的文件 "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
我怎样才能得到预期的结果?

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

【问题讨论】:

  • 您的方法不起作用,因为"{0:d2}. {1}" -f '$2', '$1' 发生在正则表达式替换之前。因为$1 是一个字符串,所以用两位数格式化它不会做任何事情,所以你最终会得到一个替换字符串'$2. $1'
  • @Ansgar Wiechers 没有围绕"{0:d2}. {1}" -f '$2', '$1' 部分的括号,格式化仍然不起作用。我还能做些什么来从这个 -replace 语法中获得预期的结果?
  • @preachers 请阅读问题顶部链接的问题的答案。

标签: powershell windows-10 powershell-v5.1


【解决方案1】:

-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

【讨论】:

  • 像魅力一样工作!谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 2020-01-25
  • 2011-05-08
  • 2012-09-14
  • 1970-01-01
相关资源
最近更新 更多