Experiencias de un programador curioso del SEO
Función de c# para dar formato a un tweet
Hara unos días creando un módulo de twitter para el CMS Cuyahoga tuve que desarrollar una función de c# para dar formato a un tweet.
Revisando el twitter he visto el excelente artículo de Alfredo Artiles sobre Expresiones regulares para dar formato a un Tweet , este excelente profesional ha desarrollado funciones para php y javascript y despues de leer su articulo se me ha ocurrido que podria compartir con vosotros la que realice para c#.
Función en c#
const string ScreenNamePattern = @"@([A-Za-z0-9\-_&;]+)";
const string HashTagPattern = @"#([A-Za-z0-9\-_&;]+)";
const string HyperLinkPattern = @"(http://\S+)\s?";
public static string FormatTweetText(string text)
{
string result = text;
if (result.Contains("http://"))
{
var links = new List<string>();
foreach (Match match in Regex.Matches(result, HyperLinkPattern))
{
var url = match.Groups[1].Value;
if (!links.Contains(url))
{
links.Add(url);
result = result.Replace(url, String.Format("<a href=\"{0}\">{0}</a>", url));
}
}
}
if (result.Contains("@"))
{
var names = new List<string>();
foreach (Match match in Regex.Matches(result, ScreenNamePattern))
{
var screenName = match.Groups[1].Value;
if (!names.Contains(screenName))
{
names.Add(screenName);
result = result.Replace("@" + screenName,
String.Format("<a href=\"http://twitter.com/{0}\">@{0}</a>", screenName));
}
}
}
if (result.Contains("#"))
{
var names = new List<string>();
foreach (Match match in Regex.Matches(result, HashTagPattern))
{
var hashTag = match.Groups[1].Value;
if (!names.Contains(hashTag))
{
names.Add(hashTag);
result = result.Replace("#" + hashTag,
String.Format("<a href=\"http://twitter.com/search?q={0}\">#{1}</a>",
HttpUtility.UrlEncode("#" + hashTag), hashTag));
}
}
}
return result;
}
Como siempre para vuestra comodidad tambien os la dejo disponible en pastebin.
| Imprimir artículo | Este artículo fue publicado por jmnieves el enero 6, 2010 a las 5:01 pm, y está archivado en .NET. Sigue las respuestas a esta entrada a través de RSS 2.0. Puedes dejar un comentario o enviar un trackback desde tu propio sitio. |