regexhelper
Test a pattern. Copy a ready-made one. No signup.

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.

/ /

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.

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.