簡體   English   中英

使用Regex將給定文本中的現有網址替換為新網址

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

我正在嘗試使用正則表達式將給定文本中的現有網址替換為新網址。 我似乎沒有與我使用的正則表達式匹配:

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

有人可以幫我寫一個正確的模式來找到類似於以下內容的網址:

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

以下是我的測試代碼,找不到與我使用的模式匹配的任何代碼:

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)\">");

除了一切看起來都很好. ? 是正則表達式中的特殊字符,因此需要轉義以將其視為文字。 所以你的表情:

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

需要是:

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

請注意前面的反斜杠. ?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM