不自动链接perl中的全数字Twitter标签?

问题描述:

我从twitter搜索结果中生成HTML。高兴地使用Net :: Twitter模块:-)不自动链接perl中的全数字Twitter标签?

Twitter中的一个规则是所有数字主题标签都不是链接。 这允许明确地鸣叫像“UR不是我的#1了”,在这里:http://twitter.com/natarias2007/status/11246320622

我想出了貌似解决方案:

$tweet =~ s{#([0-9]*[A-Za-z_]+[0-9]*)}{<a href="http://twitter.com/search?q=%23$1">#$1</a>}g; 

看来工作(我们希望) ,但我仍然好奇......你会怎么做?

编辑:我以前提出的正则表达式不正确! 请参阅下面的更好回答:-)

+0

哦。好家伙。你是否试图用正则表达式解析HTML? :o – 2010-04-22 23:42:40

+0

不,他不是。他试图用正则表达式定位散列标签,然后用HTML链接替换它们来搜索任何定位的散列标签。插入HTML,不解析它。 – 2010-04-23 09:21:12

您的正则表达式不会捕获包含由数字分隔的多个字母的锚,例如, #a0a:

my @anchors = ($tweet =~ m/#(\w+)/g); 
foreach my $anchor (@anchors) 
{ 
    next unless $anchor =~ m/[a-z]/i; 
    $tweet =~ s{#$anchor}{<a href="http://twitter.com/search?q=%23$anchor">#$anchor</a>}g; 
} 

例如,考虑my $tweet = "hello #123 hello #abc1a hello #a0a";

你的代码产生hello #123 hello <a href="http://twitter.com/search?q=%23abc1">#abc1</a>a hello <a href="http://twitter.com/search?q=%23a9">#a0</a>a

和矿山生产hello #123 hello <a href="http://twitter.com/search?q=%23abc1a">#abc1a</a> hello <a href="http://twitter.com/search?q=%23a9a">#a0a</a>

我没有意识到Twitter文字多么复杂! http://engineering.twitter.com/2010/02/introducing-open-source-twitter-text.html

我在该博客文章中链接的Ruby库中发现了这些与hashtag相关的行。不知道多少红宝石 - 可能会有更多...

# Latin accented characters (subtracted 0xD7 from the range, it's a confusable multiplication sign. Looks like "x") 
LATIN_ACCENTS = [(0xc0..0xd6).to_a, (0xd8..0xf6).to_a, (0xf8..0xff).to_a].flatten.pack('U*').freeze 
REGEXEN[:latin_accents] = /[#{LATIN_ACCENTS}]+/o 

# Characters considered valid in a hashtag but not at the beginning, where only a-z and 0-9 are valid. 
HASHTAG_CHARACTERS = /[a-z0-9_#{LATIN_ACCENTS}]/io 
REGEXEN[:auto_link_hashtags] = /(^|[^0-9A-Z&\/]+)(#|#)([0-9A-Z_]*[A-Z_]+#{HASHTAG_CHARACTERS}*)/io 

我不明白了一个道理处理`LATIN_ACCENTS”分开。如果配置正确,\ w快捷键应该可以捕获所有这些重音字符。也许这是在Ruby中不同的......也许他们有其他的原因?

现在,我解决的东西,看起来像这样

$tweet =~ s{#([0-9A-Z_]*[A-Z_]+\w+)}{<a href="http://twitter.com/search?q=%23$1">#$1</a>}gi 

不能说,这是尚未解决的..