C#根据URL中的值搜索并替换多个URL

时间:2011-05-13 15:20:12

标签: c# regex

字符串的例子:

Contrary to popular belief, <a href"mycompany/product/detail.aspx?mId=3">Lorem</a> Ipsum is not simply random text. It has roots in a piece of classical <a href"mycompany/product/detail.aspx?mId=25">Latin</a> literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin <a href"mycompany/product/detail.aspx?mId=61">professor</a> at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

字符串中有多个链接,我想要做的是根据该链接中的id 逐个替换链接。 e.g。

链接,<a href"mycompany/product/detail.aspx?mId=3">我想替换它, <a href"mycompany/detailView.aspx?pId=3">

我该怎么做?

提前谢谢!

2 个答案:

答案 0 :(得分:2)

编辑:要替换所有ID,请使用以下方法:

string pattern = @"(?<=<a[^>]+href=""mycompany/)product/detail\.aspx\?mId=(?<Id>\d+)(?="">)";
string replace = "detailView.aspx?pId=${Id}";
string result = Regex.Replace(input, pattern, replace);

该模式使用名为Id的命名组,该组捕获一个或多个数字(\d+)。然后在替换模式中引用它(即replace)。环视用于匹配常规URL模式但不捕获它,允许焦点仅在要更改的部分上。


更改特定身份证的原始答案......

要替换单个ID,您可以使用此方法:

string targetId = "3";
string pattern = @"(?<=<a[^>]+href=""mycompany/)product/detail\.aspx\?mId=(?<Id>"
                 + targetId + @")(?="">)";
string replace = "detailView.aspx?pId=${Id}";
string result = Regex.Replace(input, pattern, replace);

只需稍加努力,就可以修改上述内容以支持多个目标ID:

string[] targetIds = { "3", "61" };
string pattern = @"(?<=<a[^>]+href=""mycompany/)product/detail\.aspx\?mId=(?<Id>"
                 + String.Join("|", targetIds)
                 + @")(?="">)";
string replace = "detailView.aspx?pId=${Id}";
string result = Regex.Replace(input, pattern, replace);

这适用于数字作为ID,但是如果您计划将其扩展为常规字符串,则在加入所有目标项目之前,您将希望使用Regex.Escape method,如上所述。

答案 1 :(得分:0)

尝试这样的事情:

public string ReplaceString(string text) //Where text = the paragraph
{
     //New Text
     string newText = "<a href\"mycompany/detailView.aspx?pId=3\">";
     //Old text
     string oldText = "<a href\"mycompany/product/detail.aspx?mId=3\">";
     //String builder to replace text
     StringBuilder newString = new StringBuilder(text);
     //Replace text
     newString.Replace(oldText, newText);
     //Return
     return newString.toString();
}

我没有测试过,所以你可能需要摆弄代码。另外,您可以查看here以获取有关StringBuilder

的更多信息