Tom Gullen
Tom Gullen

Reputation: 61775

C# Regexp change link format

On my forum I have a lot of redundant link data like:

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

In regexp how can I change these to the format:

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

Upvotes: 0

Views: 412

Answers (4)

Buh Buh
Buh Buh

Reputation: 7546

This is just from memory but I will try to check it over when I have more time. Should help get you started.

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

Upvotes: 0

ChrisWue
ChrisWue

Reputation: 19070

This should capture the string \[([^\]]+)\]([^[]+)\[/\1\] and group it so you can pull out the URL like this:

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)

Upvotes: 0

Chad Grant
Chad Grant

Reputation: 45422

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

Upvotes: 4

timothyclifford
timothyclifford

Reputation: 6969

This isn't doing it totally in Regex but will still work...

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

Upvotes: 0

Related Questions