Regex to find @mentions

Use /\B@[A-Za-z0-9_]{1,15}/g to find every match in a text. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/\B@[A-Za-z0-9_]{1,15}/g
Open in Regex Tester

Sample text

Thanks @devpack and @jane_doe! Email me at jane@example.com instead.

2 matches

@devpack @jane_doe

How the pattern works

PartMeaning
\BThe @ must not follow a letter or digit, so email addresses are skipped
@The at sign
[A-Za-z0-9_]{1,15}A handle of 1–15 letters, digits or underscores (the X/Twitter limit)

Code examples

JavaScript

const matches = text.match(/\B@[A-Za-z0-9_]{1,15}/g) ?? [];

Python

import re

matches = re.findall(r'\B@[A-Za-z0-9_]{1,15}', text)

PHP

preg_match_all('/\B@[A-Za-z0-9_]{1,15}/', $text, $m);
$matches = $m[0];

Notes and limitations

Change {1,15} to the handle rules of your platform; Instagram also allows dots.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex to find @mentions?
/\B@[A-Za-z0-9_]{1,15}/g — it finds every match in a text. See the table above for what each part does.
Does it work in Python and PHP?
Yes — the code examples above use the same pattern with re in Python and preg functions in PHP.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.