Regex to Extract @mentions from Tweets and Posts

Regex to extract @username mentions from social media posts, supporting Twitter rules: 1–15 characters, ASCII letters, digits, and underscores.

Extraction

Detailed Explanation

Extracting @Mention Usernames

@username mentions appear across social platforms. Rules vary: Twitter handles are 1–15 characters of ASCII letters, digits, and underscores; GitHub handles use the same alphabet up to 39 characters; Slack allows hyphens.

Twitter-Style (1–15 chars)

(?:^|[^\w])@([A-Za-z0-9_]{1,15})(?!\w)

The leading negative class prevents matching email addresses, and the trailing negative lookahead avoids partial captures.

GitHub-Style (1–39 chars, hyphens allowed)

(?:^|[^\w])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?)(?!\w)

GitHub disallows leading or trailing hyphens.

Tested Examples

Input Twitter GitHub
"Hi @alice" alice alice
"reply to @bob_dev" bob_dev bob_dev
"@a-b-c" a-b-c
"send to user@example.com" — (preceded by word char)
"@verylonghandle1234567890 verylonghandle1 (max 15) full match

Avoid Email Address Conflicts

The most common bug is matching the @ in email addresses. The (?:^|[^\w]) prefix solves it by requiring a non-word character (or string start) before the @.

JavaScript Helper

function extractMentions(text) {
  return [...text.matchAll(/(?:^|[^\w])@([A-Za-z0-9_]{1,15})(?!\w)/g)]
    .map(m => m[1]);
}

Linking Mentions

After extraction, build profile links: https://x.com/${handle}.

Internationalization Note

Twitter recently introduced support for some non-ASCII handles in select regions, but the universal safe set is still ASCII. If you target a single platform, follow that platform’s exact rules.

Use Case

Building a notification system that pings mentioned users in comments, extracting @-mentioned authors from a tweet archive for engagement analysis, or auto-linking handles in chat exports.

Try It — Regex Cheat Sheet

Open full tool