需求: 替換網頁上所有a標簽中的鏈接. 如:<a href="http://www.asiafinance.cn" target="_blank">亞洲財經</a>, 替換成<a href="http://www.baidu.com/?to=http://www.asiafinance.cn" target="_blank">亞洲財經</a>
剛開始的做法是用Regex.Matches方法找出a標簽中所有的鏈接,然后循環Regex.Replace替換, 因為是整個頁面的全局替換, 所以,第一個鏈接替換了,第二個又來一遍,直到最后一個結束.http://tactic.asiafinance.cn/ http://tactic.asiafinance.cn/list/list_czzn.shtml,替換第一個的時候,把第二個那個鏈接也替換,后來就亂了.
這里解決方法還是Regex.Replace , 我把2個方法的代碼都貼出來.

string content = "網站內容";
string pattern = @"<a[\s\S]*?href=(""(?<href>[^""]*)""|’(?<href>[^’]*)’|(?<href>[^>\s]*))[^>]*?>";
MatchCollection mc = Regex.Matches(content,pattern,RegexOptions.IgnoreCase|RegexOptions.Compiled);
foreach (Match m in mc)
{
string url = m.Groups["href"].Value;
string replaceUrl = "http://www.baidu.com/" + "?to=" + url;
content = Regex.Replace(content,url,replaceUrl);
}

string content = "網站內容";
string pattern = @"<a[\s\S]*?href=(""(?<href>[^""]*)""|’(?<href>[^’]*)’|(?<href>[^>\s]*))[^>]*?>";
string repStr = "<a target=\"_blank\" href=\"http://www.baidu.com/?to=${href}\">";
content = Regex.Replace(content,pattern,repStr,RegexOptions.IgnoreCase|RegexOptions.Compiled);
參考內容:
替換
Regex類有一個靜態的Replace方法,其實例也有一個Replace方法,這個方法很強大,因為它可以傳入一個delegate,這樣,你可以自定義每次捕獲匹配時,如何處理捕獲的內容。
public static void Main()
{
string s = "1 12 3 5";
s = Regex.Replace(s,@"\d+",new MatchEvaluator(CorrectString),RegexOptions.Compiled|RegexOptions.IgnoreCase);
Console.WriteLine(s);
Console.ReadLine();
}
private static string CorrectString(Match match)
{
string matchValue = match.Value;
if(matchValue.Length == 1)
matchValue = "0" + matchValue;
return matchValue;
}
$number | 把匹配的第number組替換成替換表達式,還有這句話怎么寫也表達不清楚意思,還是來個例子吧: public static void Main() 這段代碼返回的是 “01 012 03 05” |
${name} | 把匹配的組名為"name"的組替換成表達式, 上例的Regex expression改成@"(?<name>\d+)(?#這個是注釋)"后面的替換式改為"0${name}"結果是一樣的 |
$$ | 做$的轉義符,如上例表達式改成@"(?<name>\d+)(?#這個是注釋)"和"$$${name}",則結果為"$1 $12 $3 $5" |
$& | 替換整個匹配 |
$` | 替換匹配前的字符 |
$' | 替換匹配后的字符 |
$+ | 替換最后匹配的組 |
$_ | 替換整個字符串 |