Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for Twitter username

Could you provide a regex that match Twitter usernames?

Extra bonus if a Python example is provided.

like image 752
Juanjo Conti Avatar asked Feb 21 '10 03:02

Juanjo Conti


People also ask

Can you use regex in Twitter search?

Can you use regex in Twitter search? Twitter unfortunately doesn't support searching of tweets using regular expressions which means that you do have to post process.

How do I verify my twitter URL?

You can verify your Twitter card in 3 easy steps: Choose the card type. Add it to your site using correct metatags. Verify the URL through the Twitter card validator for a successful log message.

How many characters can your twitter handle be?

Your username cannot be longer than 15 characters. Your name can be longer (50 characters) or shorter than 4 characters, but usernames are kept shorter for the sake of ease. A username can only contain alphanumeric characters (letters A-Z, numbers 0-9) with the exception of underscores, as noted above.


2 Answers

(?<=^|(?<=[^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 @ [email protected] @shahmirj

Matches:

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

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

like image 171
Angel.King.47 Avatar answered Sep 21 '22 16:09

Angel.King.47


If you're talking about the @username thing they use on twitter, then you can use this:

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

To make every instance an HTML link, you could do something like this:

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) 
like image 41
icktoofay Avatar answered Sep 21 '22 16:09

icktoofay