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
| Token | Description |
|---|---|
| @ | Matches the literal character '@' |
| ( | Start of capturing group |
| [a-zA-Z] | Character class — matches any one of: a-zA-Z |
| \w | Matches 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
| Input | Expected |
|---|---|
| @john_doe | Match |
| @GitHub | Match |
| no mention here | No Match |
| @user123 | Match |
| @123invalid | No Match |
Try It — Interactive Tester
Match Highlighting(3 matches)
Matches & Capture Groups
19 charsFlags: gMatches: 3Ctrl+Shift+C to copy regex