views:

26

answers:

2

i have content stored as raw text in a database that i show in a HTML table on a web site. In the content people refer to numbers and i want to have those numbers automatically become links

For example, in a field i might have

This description is for driving a car.  The manual refers to ABC:25920 and is very durable.

In this case above i want ABC:2590 to actually be an html link that translates to this html

<a href='www.mysite.com/parts/25920'>ABC:25920</a>

what is the best way of doing this. Some kind of find and replace ?? is there some other pattern matching / regex solution here?

A: 

Assumptions:
Part number is always 5 digits
Part identifier is three alpha characters.

static string RegexLinkify(string text)
{ 
    string pattern = @"(?<alphaCode>[A-Z][A-Z][A-Z]):(?<partNumber>\d{5})";
    Regex r = new Regex(pattern, RegexOptions.Singleline);
    Match matches = r.Match(text);
    string alphaCode = matches.Groups["alphaCode"].Value.ToString();
    string partNumber = matches.Groups["partNumber"].Value.ToString();
    string url = "<a href='www.mysite.com/parts/{0}'>{1}:{0}</a>";
    url = string.Format(url, alphaCode, partNumber);
    return url;

}

You can pass the data from the model to this helper method.

RandomNoob
+2  A: 

It's not clear precisely what format the numbers have. If the rule is that anything which consists of capital letters, a colon, and a number n should be turned into the link www.mysite.com/parts/n, then you can use a regex-based find-and-replace solution. You would want to look for the regex [A-Z]+:(\d+). What this says is "find one or more capital letters, a colon, and (capturing them) find one or more digits". You then want to replace this with <a href='www.mysiste.com/parts/$1'>$0</a>; in this case, $1 refers back to the capturing group (that is, the digits), and $0 refers to the whole match. I don't know C#, but I think this would look like

using System.Text.RegularExpressions;
// ...
string result = Regex.replace( getTextFromDatabase()
                             , @"[A-Z]+:(\d+)"
                             , "<a href='www.mysiste.com/parts/$1'>$0</a>");
Antal S-Z