简体   繁体   English

使用RegEx查找模式并替换

[英]Find pattern with RegEx and replace

I have the following two scenarios, where i need to replace either a href=".." value or src=".." value. 我有以下两种情况,其中我需要替换href=".."值或src=".."值。

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. GUID始终为32个字符,找到后,我需要用新值替换元素的整个href og src标记。

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 看看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. 顺便说一句,使用正则表达式来操作HTML通常是一种不好的做法,因此,如果可能的话,您可能希望摆脱这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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