user2598808
user2598808

Reputation: 643

powershell code to find and replace string

I have a string with HTML content.

I want to find few characters and replace with some other string.

For eg:

$Content = "This is my string. For more information, goto http://www.example.com/searchpage.htm. You will get the required information here. You can also get information at http://www.example.com/searchpage1.htm. Do not replace sample.htm.  Do not replace sample1.htm."

Wherever I find the text example.com, I need to replace with example1.com and the same URL contains .htm which should be made .html

If the URL does not contain example.com, I dont want to replace .htm Below is some part of code, which I could achieve to replace example.com But I am unable to replace .htm part in the same URL.

I dont want to replace .htm all over the main content. I just want to replace .htm wherever I replace example.com

$find = "http://www.example.com/"

$newContent = "http://www.example1.com/"

$replacedContent =  $Content -replace $strFind,$strReplace

I want to know how to replace a multiple parts of text in a long string.

Please suggest!

Upvotes: 2

Views: 959

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59031

Probably not the safest way (in case the URL doesn't contain .htm) but could do it for you:

$Content -replace 'http://www\.example\.com(.+?)\.html?', 'http://www.example1.com$1.html'

Upvotes: 1

Related Questions