2009-07-27 8 views
12

ハイパーリンク、ユーザー名、ハッシュタグをリンクするためにTwitterからテキストを書式設定する良い方法はありますか?私が持っているものは働いていますが、これはもっとうまくいくかもしれません。私は代替技術に興味があります。私はこれをASP.NET MVCのHTMLヘルパーとして設定しています。C#でTwitterテキスト(TweetText)を書式設定する

using System; 
using System.Collections.Generic; 
using System.Text.RegularExpressions; 
using System.Web; 
using System.Web.Mvc; 

namespace Acme.Mvc.Extensions 
{ 

    public static class MvcExtensions 
    { 
     const string ScreenNamePattern = @"@([A-Za-z0-9\-_&;]+)"; 
     const string HashTagPattern = @"#([A-Za-z0-9\-_&;]+)"; 
     const string HyperLinkPattern = @"(http://\S+)\s?"; 

     public static string TweetText(this HtmlHelper helper, string text) 
     { 
      return FormatTweetText(text); 
     } 

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

    } 

} 
+0

const string HyperLinkPattern = @ "(http(s)?:// \ S +)\ s?"; // httpsもサポート – NetProvoke

答えて

3

これは私のブログに自分のTwitterのステータスを表示するコードと非常に似ています。私がやっている唯一の事は、

です。1)@nameを探して、<a href="http://twitter.com/name">Real Name</a>に置き換えてください。

2)複数の@nameの行に複数のカンマがある場合は、複数のカンマがあります。

3)@name(s)で始まるつぶやきは、 "To @name:"の形式になります。

これは、ツイートを解析するのに有効な方法ではない理由はありません。これは非常に一貫した形式(正規表現に適しています)であり、ほとんどの場合、速度(ミリ秒)は許容以上です。

編集:

Here is the code for my Tweet parser.これは、スタックオーバーフローの答えに入れて少し長すぎるのです。それはのようなつぶやきを取ります

は@ USER1 @ user2の私はUSER3 @から得たこのクールなリンクをチェックアウト:またそれを

<span class="salutation"> 
    To <a href="http://twitter.com/user1">Real Name</a>, 
    <a href="http://twitter.com/user2">Real Name</a>: 
</span> check out this cool link I got from 
<span class="salutation"> 
    <a href="http://www.twitter.com/user3">Real Name</a> 
</span>: 
<a href="http://site.com/page.htm#anchor">http://site.com/...</a> 
<a href="http://twitter.com/#search?q=%23coollinks">#coollinks</a> 

http://url.com/page.htm#anchor #coollinks

をとに変換します小さなJavaScriptでマークアップをすべてラップします。

document.getElementById('twitter').innerHTML = '{markup}'; 

ツイートフェッチャーはJSとして非同期で実行でき、Twitterがダウンしていたり​​、遅い場合はサイトのページ読み込み時間に影響しません。

+0

URLにハッシュ文字がある場合、私のコードに問題があります。単語境界を定義するために\ bを使ってみましたが、うまくいきません。私はDjangoの例がC#で私のために働くかどうかはわかりませんが、私はそれを試しています。 – Brennan

+0

@Brennan私が言う限り、ハッシュタグは英数字にすることができます。最初にURLを取得し(#を付けたURLを捕まえる)、URL置換えが取り上げなかったフラグメントに対してハッシュタグ正規表現を実行します。 –

+0

私はRegexでC#でそれを行う方法がわかりません。例がありますか? – Brennan

0

URLを含む140文字のテキストを短縮するヘルパーメソッドを作成しました。共有の長さを0に設定して、ツイートからURLを除外することができます。

public static string FormatTwitterText(this string text, string shareurl) 
    { 
     if (string.IsNullOrEmpty(text)) 
      return string.Empty; 

     string finaltext = string.Empty; 
     string sharepath = string.Format("http://url.com/{0}", shareurl); 

     //list of all words, trimmed and new space removed 
     List<string> textlist = text.Split(' ').Select(txt => Regex.Replace(txt, @"\n", "").Trim()) 
           .Where(formatedtxt => !string.IsNullOrEmpty(formatedtxt)) 
           .ToList(); 

     int extraChars = 3; //to account for the two dots ".." 
     int finalLength = 140 - sharepath.Length - extraChars; 
     int runningLengthCount = 0; 
     int collectionCount = textlist.Count; 
     int count = 0; 
     foreach (string eachwordformated in textlist 
       .Select(eachword => string.Format("{0} ", eachword))) 
     { 
      count++; 
      int textlength = eachwordformated.Length; 
      runningLengthCount += textlength; 
      int nextcount = count + 1; 

      var nextTextlength = nextcount < collectionCount ? 
              textlist[nextcount].Length : 
              0; 

      if (runningLengthCount + nextTextlength < finalLength) 
       finaltext += eachwordformated; 
     } 

     return runningLengthCount > finalLength ? finaltext.Trim() + ".." : finaltext.Trim(); 
    } 
0

Twitterのメッセージこのリンクを解析するための優れたリソースがありますが、私の仕事:

をC#3.0

http://jes.al/2009/05/how-to-parse-twitter-usernames-hashtags-and-urls-in-c-30/

にTwitterのユーザー名、ハッシュタグやURLを解析する方法それには以下のサポートが含まれています:

  • 個のURL
  • #ハッシュ
  • @usernames

ところで:parseURLを()メソッドで正規表現を見直す必要があり、それがリンクに銘柄記号(BARC.L)を解析します。

関連する問題