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
^
and$
: Require the match to span the entire string.[A-Za-z0-9_]
: Matches a single character if it’s uppercase (A-Z
), lowercase (a-z
), digit (0-9
), or underscore (_
).+
: 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:
-
Grokking JavaScript Fundamentals
Understand closures, prototypes, async/await, and more—key to writing advanced regex logic in JS. -
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.