Replacing last occurrence of substring in string

Question:

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

Answer:

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”

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

Source:

Replacing last occurrence of substring in string by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply