regex for Twitter username

Viewed 36138

Could you provide a regex that match Twitter usernames?

Extra bonus if a Python example is provided.

11 Answers

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)

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.

The only characters accepted in the form are A-Z, 0-9, and underscore. Usernames are not case-sensitive, though, so you could use r'@(?i)[a-z0-9_]+' to match everything correctly and also discern between users.

I have used the existing answers and modified it for my use case. (username must be longer then 4 characters)

^[A-z0-9_]{5,15}$

Rules:

  • Your username must be longer than 4 characters.
  • Your username must be shorter than 15 characters.
  • Your username can only contain letters, numbers and '_'.

Source: https://help.twitter.com/en/managing-your-account/twitter-username-rules

In case you need to match all the handle, @handle and twitter.com/handle formats, this is a variation:

import re

match = re.search(r'^(?:.*twitter\.com/|@?)(\w{1,15})(?:$|/.*$)', text)
handle = match.group(1)

Explanation, examples and working regex here: https://regex101.com/r/7KbhqA/3

Matched

myhandle
@myhandle
@my_handle_2
twitter.com/myhandle
https://twitter.com/myhandle
https://twitter.com/myhandle/randomstuff

Not matched

mysuperhandleistoolong
@mysuperhandleistoolong
https://twitter.com/mysuperhandleistoolong

You can use the following regex: ^@[A-Za-z0-9_]{1,15}$

In python:

import re    
pattern = re.compile('^@[A-Za-z0-9_]{1,15}$')
pattern.match('@Your_handle')

This will check if the string exactly matches the regex.

In a 'practical' setting, you could use it as follows:

pattern = re.compile('^@[A-Za-z0-9_]{1,15}$')
if pattern.match('@Your_handle'):
    print('Match')
else:
    print('No Match')
Related