Powershell - 如何用字符串中的变量替换数字?

Powershell - How to replace a number with a variable in a string?

正在尝试使用替换运算符替换字符串中的数字(20 与变量 $cntr=120)。但是在输出中遇到了 $cntr。我哪里做错了?请有更好的解决方案。

输入字符串

myurl.com/search?project=ABC&startAt=**20**&maxResults=100&expand=log

期望的输出字符串

myurl.com/search?project=ABC&startAt=**120**&maxResults=100&expand=log

实际输出字符串

myurl.com/search?project=ABC&startAt=**$cntr**&maxResults=100&expand=log

代码:

$str='myurl.com/search?project=ABC&startAt=20&maxResults=100&expand=log'
$cntr=120
$str = $str -replace '^(.+&startAt=)(\d+)(&.+)$', '$cntr'
$str

这里有几件事:

如果您只添加“12”,您最终会得到 $112$3,这不是您想要的。我所做的是在前面附加一个斜杠,然后在后端将其删除,因此替换为 $1$3.

$str='myurl.com/search?project=ABC&startAt=20&maxResults=100&expand=log'
$cntr=12
$str = ($str -replace '^(.+&startAt=)(\d+)(&.+)$', ('\' + $cntr.ToString() +'')).Replace("\", "")
$str

想看看是否有另一种方法可以在替换部分中添加带有额外字符的文字“12”,但这确实有效。

这是另一种方法,在 $1 和 $3 之间有一个文字字符串,然后在末尾替换它。

$str='myurl.com/search?project=ABC&startAt=20&maxResults=100&expand=log'
$cntr=12
$str = ($str -replace '^(.+&startAt=)(\d+)(&.+)$', ('REPLACECOUNTER')).Replace("REPLACECOUNTER", "$cntr")
$str

你需要

  • 使用双引号可以使用字符串插值
  • 使用明确的反向引用语法${n},其中n是组ID。

在这种情况下,您可以使用

PS C:\Users\admin> $str='myurl.com/search?project=ABC&startAt=20&maxResults=100&expand=log'
PS C:\Users\admin> $cntr=120
PS C:\Users\admin> $str = $str -replace '^(.+&startAt=)(\d+)(&.+)$', "`$cntr`"
PS C:\Users\admin> $str
myurl.com/search?project=ABC&startAt=120&maxResults=100&expand=log

查看 .NET regex "Substituting a Numbered Group" documentation:

All digits that follow $ are interpreted as belonging to the number group. If this is not your intent, you can substitute a named group instead. For example, you can use the replacement string 1 instead of to define the replacement string as the value of the first captured group along with the number "1".