Code: Regex for Instagram Username and Hashtags

Instagram is unique when it comes to it’s rules for usernames and hashtags. Here is one take at create a regex to detect them in JavaScript.

The rules

  • Two matches @ mentions with no space between @thebox193@discodude
  • Matches with one . in them @disco.dude but not two .. @disco..dude
  • Ending period not matched @discodude.
  • Match underscores _ @_disco__dude_
  • Max characters of 30 @1234567890123456789012345678901234567890

The RegEx

(?:@)([A-Za-z0-9_](?:(?:[A-Za-z0-9_]|(?:\.(?!\.))){0,28}(?:[A-Za-z0-9_]))?)
Instagram username RegEx

Examples

You can try it out over onĀ Debuggex. Here is a an example implemented in JavaScript.

  • Akbar Amani

    Thank you so much, This is the best regular expression for Instagram username

  • Geo

    @JStassen, thank you for sharing this. How would you modify if you were to do it without the ‘@’? Infact, if we had to check to make sure that no one had entered the @ to say storing it in the database?

    • TheBox193

      @disqus_gm92v83kAy:disqus You should be able to just take off the first section of the regex (?:^|[^w])(?:@).

      If you’re parsing text you’re going to need to loop over your text looking for all matches, added them to an array.

      Here is an example: http://jsbin.com/rajazurofu/edit?js,console

  • Pingback: Regular Expressions | New Life()