Regex to Match @Username Mentions

Match @username mentions in social media text with this regex. Captures usernames following the @ symbol. Free online regex tester.

Regular Expression

/@([a-zA-Z]\w{0,29})/g

Token Breakdown

TokenDescription
@Matches the literal character '@'
(Start of capturing group
[a-zA-Z]Character class — matches any one of: a-zA-Z
\wMatches any word character (letter, digit, underscore)
{0,29}Matches between 0 and 29 times
)End of group

Detailed Explanation

This regex matches @username mentions as used on social media platforms like Twitter, GitHub, and Instagram. Here is the token-by-token breakdown:

@ — Matches the literal at-sign that begins every username mention. The @ character is not a regex metacharacter, so no escaping is needed.

( — Opens a capturing group for the username itself (without the @ prefix).

[a-zA-Z] — A character class matching a single letter as the first character of the username. Most platforms require usernames to start with a letter, preventing matches on email addresses or other @-prefixed tokens that start with numbers.

\w{0,29} — Matches zero to 29 additional word characters (letters, digits, underscores). Combined with the initial letter, this allows usernames of 1 to 30 characters total. This upper limit aligns with Twitter's maximum username length of 15 characters while being generous enough for other platforms.

) — Closes the capturing group.

The g flag enables global matching to find all mentions in the text. The captured group 1 contains the username without the @ prefix. This pattern matches mentions like @john_doe, @GitHub, @user123, and @OpenAI.

This pattern is commonly used in social media analytics, notification systems, and text parsing applications. It can extract mentioned usernames from posts, comments, or messages. For strict platform-specific validation, adjust the character limits and allowed characters according to the platform's rules. For example, Twitter allows only 15 characters, while GitHub allows up to 39.

Example Test Strings

InputExpected
@john_doeMatch
@GitHubMatch
no mention hereNo Match
@user123Match
@123invalidNo Match

Try It — Interactive Tester

//g
gimsuy

Match Highlighting(3 matches)

@john_doe @GitHub no mention here @user123 @123invalid

Matches & Capture Groups

#1@john_doeindex 0
Group 1:john_doe
#2@GitHubindex 10
Group 1:GitHub
#3@user123index 34
Group 1:user123
Pattern: 19 charsFlags: gMatches: 3

Ctrl+Shift+C to copy regex

Customize this pattern →