Can someone help me figure this one out, in an efficient manner?

Someone will be submitting text, in huge blocks, and I wish to have a function go through the text and search for either pre-defined tags or for http:// or www. and create a link out of it. Accepted formats to create a link would have to be these:

[a]link[/a]
[a href]link[/a href]
[ahref]link[/ahref]
[link]link[/link]
http://link.com
www.link.com

I need to loop through the current text and turn these into links. I would hate to loop through every single time, just to check for one. Is there a quicker way, as to do one pass through the text and convert all links? I attempted this with string.Replace() but with failures (as I predicted).

The reason for this is that if a user for some reason puts in 50-100 links in a 7,000 character text block, I don't want this code to loop through it 50 - 100 times. A way around this? Please let me know.

Any and all suggestions are welcome.

Recommended Answers

All 2 Replies

Regular Expressions should do the trick for this.

//Find the quotation marks in the string
Regex regEx = new Regex("[\"]");
MatchCollection mc = regEx.Matches(string);

//Remove them
foreach (Match matches in mc)
{
  string = string.Remove(matches.Index, 1);
}

It does require some looping, but it's still pretty efficient.

Here's a great resource for regular expressions:
http://regexlib.com/Default.aspx

Here was my outcome:
File: ASPX.
Characters: 54,660
Links: 1,000
Times for compiling -
First Page Load: .038695
Cap: .038695
Min: .018880
Avg: .0263867

Realistically at 6 links and 7,000 characters
(and that's over realistic for links)
Average load time: 0.001409
Avg:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.