Qaynaq LABS · TOOLS

REGEX · JAVASCRIPT

Regex explained

^[\w\.-]+@[\w\.-]+\.[a-zA-Z]{2,}$

Validates an email address format with a local part, '@', domain, and a top-level domain of at least 2 letters.

Token-by-token breakdown

TokenMeaningExample
^ Anchor: asserts position at start of the string Start of 'user@example.com'
[\w\.-]+ Character class matching one or more word characters (letters, digits, underscore), dots, or hyphens user, user.name, user-name
@ Literal '@' character @
[\w\.-]+ Character class matching one or more word characters, dots, or hyphens (domain part) example, sub.example
\. Literal '.' character (escaped) .
[a-zA-Z]{2,} Character class matching 2 or more letters (case-insensitive) com, org, io
$ Anchor: asserts position at end of the string End of 'user@example.com'

Matches

  • user@example.com
  • user.name@sub.domain.co
  • user-name@domain.org
  • a@b.co
  • user+tag@example.io

Does not match

  • user@.com
  • user@domain
  • user@domain.c
  • @example.com
  • user@example..com
  • user@example.com.
  • user@example_com

Common pitfalls

  • Does not validate internationalized email addresses (non-ASCII characters)
  • Allows consecutive dots (e.g., 'user..name@example.com') which may be invalid
  • Does not enforce length limits on the local part or domain
  • Allows hyphens at the start/end of domain parts (e.g., '-example.com')
  • Does not check for valid top-level domains (e.g., 'com' is allowed but not verified as real)

Performance notes

Low risk of catastrophic backtracking due to simple quantifiers and no nested quantifiers. Anchors ensure efficient matching.

About regular expressions

Regular expressions are tiny programs that match patterns in text. They're powerful and notoriously cryptic — most engineers can write them but few can read them confidently. Qaynaq Labs' regex explainer breaks any pattern into its constituent tokens, shows what each one does, and runs through both matching and non-matching examples so you can verify the logic.

Different regex flavors (JavaScript, PCRE, Python, Go) have subtle differences in syntax and supported features. Pick your flavor in the input — the explainer accounts for it.

Frequently asked

Does this regex validate all RFC 5322 compliant email addresses?

No. RFC 5322 allows many more characters and structures (e.g., quoted strings, comments, special characters). This is a simplified pattern.

Why is [\w\.-] used instead of [a-zA-Z0-9._-]?

In JavaScript, \w includes [a-zA-Z0-9_], so [\w\.-] is equivalent to [a-zA-Z0-9_.-] but more concise.

Can this regex match email addresses with IP addresses as domains (e.g., user@[192.168.1.1])?

No. The pattern only matches alphanumeric domains with dots and hyphens.

Why is {2,} used for the TLD instead of {2,6}?

The pattern does not enforce a maximum TLD length (e.g., '.museum' would match). {2,} allows any length ≥2.