Regex to Match an @Mention
Copy the pattern, paste text, and watch every @handle light up in group 1. Below: how it avoids matching email addresses.
Regex pattern
/(?:^|[^\w@])@(\w{1,30})/g
This matches an @mention and captures the username (up to 30 word characters) in group 1, while ignoring @ signs inside emails. Read the captured group, not the whole match, to get the handle.
What this pattern captures
Group 1 (\w{1,30}) is the handle after an @. The lookbehind-style prefix (?:^|[^\w@]) makes sure the @ is at a word boundary, so the @ inside bob@example.com is skipped.
Part by part
(?:^|[^\w@]) — start of string or a non-word, non-@ character before the @.
@ — the literal at-sign.
(\w{1,30}) — the handle: letters, digits and underscores, 1 to 30 long.
Why not a simple @\w+
A bare @\w+ also grabs the domain-less part of email addresses. Requiring a boundary before the @ avoids that false positive.
Use it in your code
import re
text = "Thanks @jane_doe and @team01! Email me at bob@example.com (should NOT match as a handle)."
pattern = r'''(?:^|[^\w@])@(\w{1,30})'''
for m in re.finditer(pattern, text):
print(m.group())
const text = "Thanks @jane_doe and @team01! Email me at bob@example.com (should NOT match as a handle).";
const re = new RegExp(String.raw`(?:^|[^\w@])@(\w{1,30})`, "g");
console.log(text.match(re));
FAQ
Why does it skip emails?
The (?:^|[^\w@]) prefix requires the @ to follow a boundary, so the @ inside an email (preceded by a word character) is not matched.
Where is the handle in the result?
In capture group 1. The full match includes the boundary character, so read match[1] for the name.
Can I allow longer handles?
Change {1,30} to the length your platform allows, e.g. {1,15} for classic Twitter handles.