brother
brother

Reputation: 8171

Find pattern with RegEx and replace

I have the following two scenarios, where i need to replace either a href=".." value or src=".." value.

The pattern is

The GUID is always 32 charaters long, and when found, I need to replace the entire href og src tag, of the element, with a new value.

Any ideas as to how this can be done?

Upvotes: 0

Views: 57

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

This is the pattern you need:

(src="(\/~\/media\/([A-Z0-9]{32})\.ashx)")|(href="(\/~\/link\.aspx\?_id=([A-Z0-9]{32})&_z=z"))

Have a look at DEMO

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522254

Here is code for replacing the image tags as you described:

string input = "<img src="/~/media/75F8BA07F3BC4C3F91A71D6A049E6BD4.ashx" alt="" />";
input = Regex.Replace(input,
                      @"<img [^>]*src=""/~/([^/]+)/[A-Z0-9]{32}[^""]*""[^>]*/>",
                      "<img src=\"/$1/myfolder/myimage.png\" alt=\"\" />");

I would do a separate replacement on the anchor tags, and I will leave this to you as a follow up exercise.

By the way, it is in general bad practice to manipulate HTML using regular expressions, so you might want to move away from this if possible.

Upvotes: 0

Related Questions