2011-04-11 48 views
0

在我的論壇上,我有很多的冗餘鏈路的數據,如:C#正則表達式更改鏈接的格式

[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7] 

在正則表達式我如何可以改變這些的格式:

<a href="http://www.box.net/shared/0p28sf6hib" rel="nofollow">http://www.box.net/shared/0p28sf6hib</a> 

回答

4
string orig = "[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; 
string replace = "<a href=\"$1\" rel=\"nofollow\">$1</a>"; 
string regex = @"\[url:.*?](.*?)\[/url:.*?]"; 

string fixedLink = Regex.Replace(orig, regex, replace); 
0

這應該捕捉字符串\[([^\]]+)\]([^[]+)\[/\1\]並將其分組,以便您可以像這樣取出網址:

Regex re = new Regex(@"\[([^\]]+)\]([^[]+)\[/\1\]"); 
var s = @"[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; 
var replaced = s.Replace(s, string.Format("<a href=\"{0}\" rel=\"nofollow\">{0}</a>", re.Match(s).Groups[1].Value)); 
Console.WriteLine(replaced) 
0

這不是完全完成在正則表達式,但仍然會工作...

string oldUrl = "[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]"; 
Regex regExp = new Regex(@"http://[^\[]*"); 
var match = regExp.Match(oldUrl); 
string newUrl = string.Format("<a href='{0}' rel='nofollow'>{0}</a>", match.Value); 
0

這僅僅是從內存,但我會盡力檢查過,當我有更多的時間。應該幫助你開始。

string matchPattern = @"\[(url\:\w)\](.+?)\[/\1\]"; 
String replacePattern = @"<a href='$2' rel='nofollow'>$2</a>"; 
String blogText = ...; 
blogText = Regex.Replace(matchPattern, blogText, replacePattern);