🔍Regex Recipes

Extract @Mentions

Extract social media @mentions and @usernames from text.

Pattern

@[\w]{1,15}

Explanation

Matches @ followed by 1-15 word characters (letters, numbers, underscore). Common for Twitter/X usernames.

Examples

Simple mention
Input
@username
Output
✓ Match
In sentence
Input
Hey @john_doe how are you?
Output
✓ Match: @john_doe
Multiple
Input
@alice and @bob
Output
Matches both
Too long
Input
@verylongusernamethatexceedslimit
Output
✓ Match first 15 chars only

Code Examples

JavaScript
const text = 'Thanks @john_doe and @alice for the help!';
const mentions = text.match(/@[\w]{1,15}/g)
  .map(m => m.substring(1)); // Remove @
// Result: ['john_doe', 'alice']

// With word boundaries for precision
const preciseMentions = /\B@[\w]{1,15}\b/g;

// Extract with position info
const matches = [...text.matchAll(/@([\w]{1,15})/g)];
matches.forEach(([full, username], index) => {
  console.log(`Found @${username} at position ${matches[index].index}`);
});

Try it Now

💡 Tips

  • Twitter/X: 1-15 characters, letters/numbers/underscore
  • Instagram: allows dots, 1-30 characters
  • Use \B@\w+ to avoid matching email addresses
  • Validate against actual user database

⚠️ Common Pitfalls

  • Username length limits vary by platform
  • May match @ in email addresses
  • Some platforms allow dots or dashes
  • Use word boundary \B to avoid matching in emails