2015-02-10 182 views

回答

5

正则表达式也可以执行此任务。这是一个可以工作的例子。它将与“大黄蜂乔”

$text = "This is the dawning of the age of Aquarius. The age of Aquarius, Aquarius, Aquarius, Aquarius, Aquarius" 
$text -replace "(.*)Aquarius(.*)", '$1Bumblebee Joe$2' 
This is the dawning of the age of Aquarius. The age of Aquarius, Aquarius, Aquarius, Aquarius, Bumblebee Joe 

取代“水瓶座”的最后出现的贪婪量词确保采取一​​切所能,直到的Aquarius的最后一场比赛。 $1$2代表匹配前后的数据。

如果您正在使用您需要使用双引号和逃避$的正则表达式替换,以便PowerShell不会试图把他们当作一个变量

$replace = "Bumblebee Joe" 
$text -replace "(.*)Aquarius(.*)", "`$1$replace`$2" 
+0

它似乎只适用于替换字符串是文字。 – nickm 2015-02-10 17:56:29

+0

这是唯一的情况,因为它被括在单引号中。我可以更新答案来解释这一点。 – Matt 2015-02-10 18:05:45

+0

现在它完美的工作。谢谢。 – nickm 2015-02-11 07:39:18

2

Using the exact same technique as I would in C#

function Replace-LastSubstring { 
    param(
     [string]$str, 
     [string]$substr, 
     [string]$newstr 
    ) 

    return $str.Remove(($lastIndex = $str.LastIndexOf($substr)),$substr.Length).Insert($lastIndex,$newstr) 
} 
+0

是什么'$ newstr'更换一个变量?你不只需要用户正在寻找的原始字符串和子字符串? – 2017-11-07 00:19:05

+0

OP需要*替换*子字符串,而不仅仅是删除它 – 2017-11-07 08:29:31

相关问题