Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex: @mentions
Regex pattern · find & extract

Regex: @mentions

Regex for @mentions: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /(?<!\w)@\w{1,15}/g with the global flag to find every match. In "Thanks @jack and @x_dev! Email me@example.com" it finds "@jack", "@x_dev". Adjust {1,15} to your platform’s username length.

Last updated · Maintained by FreeAIToolz · How we test

/(?<!\w)@\w{1,15}/g

2 match(es)

Thanks @jack and @x_dev! Email me@example.com
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
(?<!\w)not preceded by a word character, so email addresses are skipped
@the @ sign
\w{1,15}a handle of up to 15 characters

Flags: g finds every match instead of stopping at the first.

Examples

InputMatches
Thanks @jack and @x_dev! Email me@example.com@jack, @x_dev

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

Adjust {1,15} to your platform’s username length.

When to use this pattern

Linking or notifying users mentioned in comments and chat messages.

Use it in your language

JavaScript

const matches = text.match(/(?<!\w)@\w{1,15}/g) ?? [];

Python

import re
matches = [m.group(0) for m in re.finditer(r'(?<!\w)@\w{1,15}', text)]

PHP

preg_match_all('~(?<!\\w)@\\w{1,15}~', $text, $m);
$matches = $m[0];

Java

Matcher m = Pattern.compile("(?<!\\w)@\\w{1,15}").matcher(text);
while (m.find()) { System.out.println(m.group()); }

Go’s regexp package (RE2) does not support lookahead or lookbehind, so this exact pattern will not compile in Go.

More regex patterns

Frequently asked questions

What is the regex for @mentions?
/(?<!\w)@\w{1,15}/g. Adjust {1,15} to your platform’s username length.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It does not work in Go, because RE2 has no lookaround support.
How do I replace the matches?
In JavaScript use text.replace(/(?<!\w)@\w{1,15}/g, "replacement"); in Python use re.sub(r'(?<!\w)@\w{1,15}', "replacement", text).