Regular expression for alphanumeric and underscores
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
The regex pattern ^\w+$ matches a string that contains only alphanumeric characters (letters and digits) and underscores. The \w shorthand is equivalent to [A-Za-z0-9_] in most regex engines. Use ^\w+$ when the entire string must conform to this character set, and \w+ when you want to extract matching substrings from a larger text.
Breaking Down the Pattern
| Component | Meaning |
^ | Anchors the match to the start of the string |
\w | Matches one character: [A-Za-z0-9_] |
+ | Requires one or more of the preceding token |
$ | Anchors the match to the end of the string |
Without the ^ and $ anchors, the pattern matches any substring that fits, which means "hello world" would match the hello portion. The anchors ensure the entire string consists exclusively of word characters.
The \w Shorthand in Detail
\w is defined by the regex engine, and its exact behavior varies between implementations:
| Engine / Language | \w Matches |
Python (re) | [A-Za-z0-9_] (ASCII mode) |
Python (re.UNICODE) | Unicode letters, digits, underscore |
| JavaScript | [A-Za-z0-9_] (always ASCII) |
| Java | [A-Za-z0-9_] by default, Unicode with UNICODE_CHARACTER_CLASS |
| PCRE (PHP, Perl) | [A-Za-z0-9_] by default, Unicode with /u flag |
| .NET (C#) | Unicode letters, digits, underscore by default |
In Python 3, re uses Unicode matching by default. This means \w matches accented characters like e or u, CJK characters, and other Unicode letter categories. If you want strict ASCII-only matching, use re.ASCII or the (?a) inline flag:
Using the Explicit Character Class
When you need precise control over what matches, spell out the character class instead of relying on \w:
The explicit form is self-documenting and immune to differences in how regex engines interpret \w. It is the safer choice in cross-platform codebases.
Common Validation Patterns
Username Validation
Most platforms restrict usernames to alphanumeric characters and underscores, with length constraints:
Variable Name Validation
Programming identifiers typically follow similar rules. In most languages, identifiers cannot start with a digit:
Database Column Name Validation
When building dynamic SQL (with proper parameterization for values), column names often need to be validated against injection:
Quantifiers with \w
Control how many characters the pattern matches using quantifiers:
| Pattern | Matches | Example |
\w | Exactly one word character | a |
\w+ | One or more word characters | hello_world |
\w* | Zero or more word characters | `` (empty) or abc |
\w{4} | Exactly four word characters | abcd |
\w{2,8} | Between two and eight word characters | ab, abcdefgh |
\w{3,} | Three or more word characters | abc, abcdef |
Examples Across Languages
The Inverse: \W
\W (uppercase) matches any character that is NOT a word character. It is the complement of \w, equivalent to [^A-Za-z0-9_]:
This is useful for sanitizing user input into identifier-safe strings.
Common Pitfalls
Assuming \w is ASCII-only in Python 3. By default, Python 3's re module matches Unicode letters with \w. The string "cafe" passes ^\w+$ because the accented e is a Unicode letter. Use re.ASCII or (?a) if you need strict ASCII matching.
Forgetting anchors and getting partial matches. Without ^ and $, re.search(r'\w+', "hello world!") matches hello (a substring), not the entire string. Always use anchors for full-string validation. In Python, re.fullmatch(r'\w+', text) is cleaner than re.match(r'^\w+$', text).
Allowing strings that start with a digit when validating identifiers. The pattern ^\w+$ allows 123abc, which is not a valid identifier in most programming languages. Use ^[A-Za-z_]\w*$ to require a letter or underscore as the first character.
Double-escaping in Java strings. Java string literals require \\w because \ is an escape character in both Java strings and regex. Writing "\w" in Java produces an invalid escape sequence. Always use "\\w" in Java regex strings.
Using \w for email or URL validation. \w does not match dots, hyphens, or @ symbols. It is not suitable for validating emails, domain names, or URLs. Use purpose-built patterns or validation libraries for those.
Overlooking locale-dependent behavior in PCRE. In PHP's preg_match, \w matches only ASCII by default. Adding the /u flag enables Unicode matching, which changes the set of characters that pass the pattern.
Summary
\wmatches[A-Za-z0-9_]in most regex engines, but some default to Unicode letter matching (Python 3, .NET).- Use
^\w+$for full-string validation and\w+for substring extraction. - Spell out
[A-Za-z0-9_]explicitly when cross-platform consistency matters. - Add a leading
[A-Za-z_]to the pattern when validating programming identifiers that must not start with a digit. - Use
\W(uppercase) to match or replace non-word characters. - Always test your pattern against edge cases: empty strings, Unicode input, strings starting with digits, and strings containing hyphens or dots.
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.