简体   繁体   中英

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

  • <img src="/~/media/75F8BA07F3BC4C3F91A71D6A049E6BD4.ashx" alt="" />
  • <a href="/~/link.aspx?_id=2CD5F3FBD0334A7DA7CB81F9520BEED5&amp;_z=z">Some text</a>

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?

This is the pattern you need:

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

Have a look at DEMO

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM