Alex Rivera | Logout

regex for Twitter username

Asked 2010-02-21T03:19:46.123
50

Could you provide a regex that match Twitter usernames?

Extra bonus if a Python example is provided.

Edit
Report

4 Answers

80
(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9-_]+)

I've used this as it disregards emails.

Here is a sample tweet:

@Hello how are @you doing @my_friend, email @000 me @ whats.up@example.com @shahmirj

Matches:

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

It will also work for hashtags, I use the same expression with the @ changed to #.

answered 2011-06-15T01:01:13.223
13

Twitter recently released to open source in various languages including Java, Ruby (gem) and Javascript implementations of the code they use for finding user names, hash tags, lists and urls.

It is very regular expression oriented.

answered 2010-02-24T22:55:59.960
2

This is a method I have used in a project that takes the text attribute of a tweet object and returns the text with both the hashtags and user_mentions linked to their appropriate pages on twitter, complying with the most recent twitter display guidelines

def link_tweet(tweet):
"""
This method takes the text attribute from a tweet object and returns it with
user_mentions and hashtags linked
"""
tweet = re.sub(r'(\A|\s)@(\w+)', r'\1@<a href="http://www.twitter.com/\2">\2</a>', str(tweet))
return re.sub(r'(\A|\s)#(\w+)', r'\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', str(tweet))

Once you call this method you can pass in the param my_tweet[x].text. Hope this is helpful.

answered 2013-02-20T21:00:04.393
1

Shorter, /@([\w]+)/ works fine.

answered 2010-02-24T23:19:47.757

Your Answer