Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用正则表达式解析tweet文本_C#_Regex_Twitter - Fatal编程技术网

C# 用正则表达式解析tweet文本

C# 用正则表达式解析tweet文本,c#,regex,twitter,C#,Regex,Twitter,这里是Regex noob。寻找一些C#regex代码来“语法突出显示”twitter文本。鉴于这条推文: @taglius here's some tweet text that shouldn't be highlighted #tagtestpix http://aurl.jpg 我想找到用户提到的(@)、hashtags(#)和URL(http://),并添加适当的html以颜色突出显示这些元素。差不多 <font color=red>@taglius</font&g

这里是Regex noob。寻找一些C#regex代码来“语法突出显示”twitter文本。鉴于这条推文:

@taglius here's some tweet text that shouldn't be highlighted #tagtestpix http://aurl.jpg
我想找到用户提到的(@)、hashtags(#)和URL(http://),并添加适当的html以颜色突出显示这些元素。差不多

<font color=red>@taglius</font> here's some tweet text that shouldn't be highlighted   <font  color=blue>#tagtestpix</font> <font color=yellow>http://aurl.jpg</font>
@taglius这里有一些不应该突出显示的tweet文本#tagtestpixhttp://aurl.jpg

这不是我将使用的确切的html,但我想你明白了。

你可以使用(\@\w+)解析出@reples。您可以使用(#\w+)解析出哈希标记。

以下内容将匹配“@”字符,后跟一系列alpha-num字符:

@\w+
\#\w+

以下内容将匹配“#”字符,后跟一系列alpha-num字符:

@\w+
\#\w+
有很多自由格式的http url匹配表达式,这是我最常用的一种:

https?://[-\w]+(\.\w[-\w]*)+(:\d+)?(/[^.!,?;""\'<>()\[\]\{\}\s\x7F-\xFF]*([.!,?]+[^.!,?;""\'<>\(\)\[\]\{\}\s\x7F-\xFF]+)*)?
显然,这将是一个问题,因为所有三个表达式都将在url内匹配。为了避免这种情况,您需要弄清楚在匹配之前或之后允许哪些字符。例如,以下内容要求@name引用前面有一个空格或字符串开头,并要求后面有一个“,”或空格

(?<=[^\s])@\w+(?=[,\s])

(?以上答案是整个答案的一部分,因此我想我可以补充一点来回答您的问题:

突出显示函数的外观如下所示:

public static String HighlightTwitter(String input)
{
    String result = Regex.Replace(input, @"\b\@\w+", @"<font color=""red"">$0</font>");
    result = Regex.Replace(result, @"\b#\w+", @"<font color=""blue"">$0</font");
    result = Regex.Replace(result, @"\bhttps?://[-\w]+(\.\w[-\w]*)+(:\d+)?(/[^.!,?;""\'<>()\[\]\{\}\s\x7F-\xFF]*([.!,?]+[^.!,?;""\'<>\(\)\[\]\{\}\s\x7F-\xFF]+)*)?\b", @"<font color=""yellow"">$0</font", RegexOptions.IgnoreCase);
    return result;
}
publicstaticstringhighlighttwitter(字符串输入)
{
字符串结果=Regex.Replace(输入@“\b\@\w+”,@“$0”);

result=Regex.Replace(result,@“\b#\w+”,@“$0注意到。我已经检查并接受了我以前问题的答案。感谢您的帮助。谢谢您,先生。社区从您的慷慨中受益=)这两条评论都引导我走向正确的方向,我选择了这一条,因为它更完整。