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

本文关键字:URL 替换 搜索 根据 | 更新日期: 2023-09-27 17:56:35

字符串的例子:

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 逐个替换链接。 例如

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

我该怎么做?

提前谢谢你!

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

编辑:要替换所有 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 的原始答案...

要替换单个 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 方法,就像我上面所做的那样。

尝试这样的事情:

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();
}

我还没有测试过它,所以你可能需要摆弄代码。您也可以在此处查看有关StringBuilder

的更多信息