简体   繁体   English

使用Regex将给定文本中的现有网址替换为新网址

[英]Replace an existing url in given text with a new url using Regex

I'm trying to replace an existing url in given text with a new url using regex. 我正在尝试使用正则表达式将给定文本中的现有网址替换为新网址。 I don't seem to get any matches for the regex pattern I'm using: 我似乎没有与我使用的正则表达式匹配:

string regex = "<a href=\"http://domain/page.asp?id=(\\d+)&amp;oid=(\\d+)&amp;type=(\\w+)\">";

Can someone please assist me write a correct pattern to find urls that look like: 有人可以帮我写一个正确的模式来找到类似于以下内容的网址:

"<A href=\"http://domain/page.asp?id=38957&amp;oid=2497&amp;type=JPG\">"

Below is my test code which cannot find any matches for the pattern I'm using: 以下是我的测试代码,找不到与我使用的模式匹配的任何代码:

string result = string.Empty;

string sampleText = "<A href=\"http://domain/page.asp?id=38957&amp;oid=2497&amp;type=JPG\"><U>Click here for Terms &amp; Conditions...</U></A>";

string regex = "<a href=\"http://domain/page.asp?id=(\\d+)&amp;oid=(\\d+)&amp;type=(\\w+)\">";
        Regex regEx = new Regex(regex, RegexOptions.IgnoreCase);

result= regEx.Replace(text, "<a href=\"/newPage/Index/$1&opid=$2)\">");

Everything looks fine except that . 除了一切看起来都很好. and ? ? are special characters in regular expressions, so they need to be escaped to be treated as literals. 是正则表达式中的特殊字符,因此需要转义以将其视为文字。 So your expression: 所以你的表情:

string regex = "<a href=\"http://domain/page.asp?id=(\\d+)&amp;oid=(\\d+)&amp;type=(\\w+)\">";

Needs to be: 需要是:

string regex = "<a href=\"http://domain/page\\.asp\\?id=(\\d+)&amp;oid=(\\d+)&amp;type=(\\w+)\">";

Note the backslashes in front of the . 请注意前面的反斜杠. and ? ? .

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

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