Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing last occurrence of substring in string

How can you replace the last occurrence of a substring in a string?

like image 588
nickm Avatar asked Feb 10 '15 16:02

nickm


3 Answers

Regular Expressions can also perform this task. Here is an example of one that would work. It will replace the last occurrence of "Aquarius" with "Bumblebee Joe"

$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

The greedy quantifier ensure that it take everything it can up until the last match of Aquarius. The $1 and $2 represent the data before and after that match.

If you are using a variable for the replacement you need to use double quotes and escape the $ for the regex replacements so PowerShell does not try to treat them as a variable

$replace = "Bumblebee Joe"
$text -replace "(.*)Aquarius(.*)", "`$1$replace`$2"
like image 127
Matt Avatar answered Oct 10 '22 02:10

Matt


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)
}
like image 36
Mathias R. Jessen Avatar answered Oct 10 '22 02:10

Mathias R. Jessen


print(str1[::-1].replace("xx","rr",1)[::-1])

like image 43
pbeginner Avatar answered Oct 10 '22 04:10

pbeginner