Logo

Is there a regular expression which checks if a string contains only upper and lowercase letters, numbers, and underscores?

Yes! One straightforward way is to use a character class that includes upper case letters, lower case letters, digits, and underscores, then anchor it to start (^) and end ($) of string. For example:

^[A-Za-z0-9_]+$

Explanation

  1. ^ and $: Require the match to span the entire string.
  2. [A-Za-z0-9_]: Matches a single character if it’s uppercase (A-Z), lowercase (a-z), digit (0-9), or underscore (_).
  3. +: Requires one or more of these allowed characters. (If you want to allow an empty string as valid, use * instead of +.)

Examples

  • "Hello123" ✅ matches (letters + digits).
  • "Hello_123" ✅ matches (letters + underscore + digits).
  • "Hello-123" ❌ fails (hyphen not allowed).
  • "" ❌ fails (empty string requires * if you want it allowed).

Alternative: ^\w+$

Depending on your regex engine, you might consider:

^\w+$
  • In many engines, \w means [A-Za-z0-9_].
  • However, some flavors treat \w more broadly (e.g., including accented letters in Unicode mode). If you need strictly [A-Za-z0-9_], the explicit [A-Za-z0-9_] character class is safer.

Bonus: Strengthen Your JavaScript & Coding Skills

If you’re exploring regex and JavaScript, or preparing for coding interviews, check out these DesignGurus.io courses:

  1. Grokking JavaScript Fundamentals
    Understand closures, prototypes, async/await, and more—key to writing advanced regex logic in JS.

  2. Grokking the Coding Interview: Patterns for Coding Questions
    Practice common coding patterns for real-world problems and interview success.

For personalized feedback, explore Mock Interviews with ex-FAANG engineers:

And don’t miss free educational content on the DesignGurus.io YouTube channel.

CONTRIBUTOR
TechGrind