Twitter用户名的正则表达式

50 投票
11 回答
38174 浏览
提问于 2025-04-15 19:32

你能提供一个正则表达式,用来匹配推特用户名吗?

如果能给个Python的例子,那就更好了。

11 个回答

19

我使用的正则表达式,已经在多个场景中测试过:

/(^|[^@\w])@(\w{1,15})\b/

这是我找到的测试和替换Twitter用户名的最简单方法。

#!/usr/bin/python

import re

text = "@RayFranco is answering to @jjconti, this is a real '@username83' but this is an@email.com, and this is a @probablyfaketwitterusername";

ftext = re.sub( r'(^|[^@\w])@(\w{1,15})\b', '\\1<a href="http://twitter.com/\\2">\\2</a>', text )

print ftext;

这将会按我预期的返回结果:

<a href="http://twitter.com/RayFranco">RayFranco</a> is answering to <a href="http://twitter.com/jjconti">jjconti</a>, this is a real '<a href="http://twitter.com/username83">username83</a>' but this is an@email.com, and this is a @probablyfaketwitterusername

根据Twitter的规定

你的用户名不能超过15个字符。你的真实姓名可以更长(最多20个字符),但为了方便,用户名保持较短。用户名只能包含字母(A-Z)和数字(0-9),除了下划线以外的符号都不能用。确保你想要的用户名没有任何符号、连字符或空格。

21

如果你在说Twitter上用的那个@用户名的方式,那么你可以这样做:

import re
twitter_username_re = re.compile(r'@([A-Za-z0-9_]+)')

如果你想把每一个实例都变成一个HTML链接,你可以这样做:

my_html_str = twitter_username_re.sub(lambda m: '<a href="http://twitter.com/%s">%s</a>' % (m.group(1), m.group(0)), my_tweet)
80
(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9-_]+)

我用这个方法是因为它可以忽略电子邮件。

这里有一个示例推文:

@Hello 你怎么样 @you @my_friend,电子邮件 @000 给我 @ whats.up@example.com @shahmirj

匹配到的内容有:

  • @Hello
  • @you
  • @my_friend
  • @shahmirj

这个方法也适用于话题标签,我只需把 @ 改成 # 就可以了。

撰写回答