Regular Expressions
Alphanumeric
Underscores
Coding
Syntax

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.

Browse interview questions

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.

python
1import re
2
3# Validate that a string contains only alphanumeric chars and underscores
4pattern = r'^\w+$'
5
6print(re.match(pattern, "user_name_42"))   # Match
7print(re.match(pattern, "hello world"))    # None (space is not \w)
8print(re.match(pattern, "[email protected]")) # None (@ and . are not \w)

Breaking Down the Pattern

ComponentMeaning
^Anchors the match to the start of the string
\wMatches 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:

python
1import re
2
3# Default Python 3: \w matches Unicode letters
4print(re.match(r'^\w+$', "cafe"))     # Match (accent included)
5
6# ASCII-only mode
7print(re.match(r'(?a)^\w+$', "cafe")) # None (accent excluded)

Using the Explicit Character Class

When you need precise control over what matches, spell out the character class instead of relying on \w:

python
1# Strict ASCII alphanumeric + underscore
2pattern = r'^[A-Za-z0-9_]+$'
3
4# Case-insensitive (reduces the class)
5pattern = r'^[a-z0-9_]+$'  # with re.IGNORECASE

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:

python
1import re
2
3def validate_username(username):
4    """3-20 characters, alphanumeric and underscores, must start with a letter."""
5    pattern = r'^[A-Za-z]\w{2,19}$'
6    return bool(re.match(pattern, username))
7
8print(validate_username("john_doe"))    # True
9print(validate_username("_john"))       # False (starts with underscore)
10print(validate_username("ab"))          # False (too short)
11print(validate_username("a" * 21))      # False (too long)

Variable Name Validation

Programming identifiers typically follow similar rules. In most languages, identifiers cannot start with a digit:

javascript
// JavaScript: validate identifier-like strings
const isValidIdentifier = /^[A-Za-z_]\w*$/.test(name);
java
// Java: validate identifier
boolean isValid = name.matches("^[A-Za-z_]\\w*$");

Database Column Name Validation

When building dynamic SQL (with proper parameterization for values), column names often need to be validated against injection:

python
1import re
2
3def is_safe_column_name(name):
4    """Only allow alphanumeric and underscores for column names."""
5    return bool(re.match(r'^[A-Za-z_][A-Za-z0-9_]{0,63}$', name))

Quantifiers with \w

Control how many characters the pattern matches using quantifiers:

PatternMatchesExample
\wExactly one word charactera
\w+One or more word charactershello_world
\w*Zero or more word characters`` (empty) or abc
\w{4}Exactly four word charactersabcd
\w{2,8}Between two and eight word charactersab, abcdefgh
\w{3,}Three or more word charactersabc, abcdef

Examples Across Languages

python
1# Python: extract all word tokens from text
2import re
3tokens = re.findall(r'\w+', "Hello, world_2024! foo-bar")
4# ['Hello', 'world_2024', 'foo', 'bar']
javascript
// JavaScript: same extraction
const tokens = "Hello, world_2024! foo-bar".match(/\w+/g);
// ['Hello', 'world_2024', 'foo', 'bar']
java
// Java: split on non-word characters
String[] tokens = "Hello, world_2024! foo-bar".split("\\W+");
// ["Hello", "world_2024", "foo", "bar"]

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_]:

python
1import re
2
3# Replace all non-word characters with underscores
4cleaned = re.sub(r'\W+', '_', "Hello, World! 2024")
5print(cleaned)  # Hello_World_2024

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

  • \w matches [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.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions