Der*_*ker 5 c# asp.net twitter tweetsharp
我最近从TweetSharp切换到LinqToTwitter,我遗漏的一件事就是以HTML格式检索推文.
TweetSharp有一个名为.TextAsHtml()自动链接提及,哈希标记和超链接的方法.
有谁知道LinqtoTwitter中是否存在这样的功能?任何有关TweetSharp如何实现这一目标的见解都会受到很多关注.
更新:
看起来TweetSharp使用正则表达式来匹配URL,提及和哈希标记.这是一个示例:
private static readonly Regex _parseUrls = new Regex("\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^\\p{P}\\s]|/)))", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _parseMentions = new Regex("(^|\\W)@([A-Za-z0-9_]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _parseHashtags = new Regex("[#]+[A-Za-z0-9-_]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
Run Code Online (Sandbox Code Playgroud)
Der*_*ker 18
这是我的最终解决方案,它使用TweetSharp库中的一些逻辑.它运作得很好:
/// <summary>
/// Extends the LinqToTwitter Library
/// </summary>
public static class TwitterExtensions
{
private static readonly Regex _parseUrls = new Regex("\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^\\p{P}\\s]|/)))", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _parseMentions = new Regex("(^|\\W)@([A-Za-z0-9_]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _parseHashtags = new Regex("[#]+[A-Za-z0-9-_]+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Parse Status Text to HTML equivalent
/// </summary>
/// <param name="status">The LinqToTwitter <see cref="Status"/></param>
/// <returns>Formatted HTML string</returns>
public static string TextAsHtml(this Status status)
{
string tweetText = status.Text;
if (!String.IsNullOrEmpty(tweetText))
{
// Replace URLs
foreach (var urlMatch in _parseUrls.Matches(tweetText))
{
Match match = (Match)urlMatch;
tweetText = tweetText.Replace(match.Value, String.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value));
}
// Replace Mentions
foreach (var mentionMatch in _parseMentions.Matches(tweetText))
{
Match match = (Match)mentionMatch;
if (match.Groups.Count == 3)
{
string value = match.Groups[2].Value;
string text = "@" + value;
tweetText = tweetText.Replace(text, String.Format("<a href=\"http://twitter.com/{0}\" target=\"_blank\">{1}</a>", value, text));
}
}
// Replace Hash Tags
foreach (var hashMatch in _parseHashtags.Matches(tweetText))
{
Match match = (Match)hashMatch;
string query = Uri.EscapeDataString(match.Value);
tweetText = tweetText.Replace(match.Value, String.Format("<a href=\"http://search.twitter.com/search?q={0}\" target=\"_blank\">{1}</a>", query, match.Value));
}
}
return tweetText;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1929 次 |
| 最近记录: |