PatternRegex

Match an @mention

Find @mentions in comments or chat logs, handy for building notifications, though email addresses need a guard.

Last updated

Patterng
@[A-Za-z0-9_]+
Open in Regex Tester & Builder

Matches

  • Thanks @alice for the review
  • cc @bob_dev on this

Doesn’t match

  • Reach out via the contact form
  • Just an at symbol alone here

Why it’s written this way

The @ is literal, and [A-Za-z0-9_]+ after it matches one or more username characters, covering the letters, digits, and underscore that platforms like GitHub, Slack, and X allow in a handle.

There's no check on what comes before the @, so it fires on any @ in the text that's followed by word characters, not only ones sitting at the start of a word.

Edge cases to know

  • The biggest gap: an email address like jane@example.com contains an @ followed by word characters, so this pattern matches '@example' inside it as though it were a mention. Guarding against that needs a negative lookbehind for a preceding word character, such as (?<!\w)@[A-Za-z0-9_]+, which refuses to start the match when the @ is glued onto an existing word.
  • It doesn't allow dots or hyphens in the handle, so a platform that permits those in usernames would need a wider character class.

Related in Patterns