开发者

Automatic formatting in web page content

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜