在我的论坛上,我有很多的冗余链路的数据,如: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>
在我的论坛上,我有很多的冗余链路的数据,如: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>
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);
这应该捕捉字符串\[([^\]]+)\]([^[]+)\[/\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)
这不是完全完成在正则表达式,但仍然会工作...
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);
这仅仅是从内存,但我会尽力检查过,当我有更多的时间。应该帮助你开始。
string matchPattern = @"\[(url\:\w)\](.+?)\[/\1\]";
String replacePattern = @"<a href='$2' rel='nofollow'>$2</a>";
String blogText = ...;
blogText = Regex.Replace(matchPattern, blogText, replacePattern);