Course contentsShow
← Java
Lesson 2297 of 2,87044. Regular ExpressionsFree lesson

Predefined Character Classes: \d, \w, \s

Master shorthand classes for digits, word characters, whitespace, and their negated forms (\D, \W, \S).

Predefined Character Classes: \d, \w, \s

You'll learn shorthand character classes that make common regex patterns shorter and more readable.

What Are Predefined Character Classes?

Instead of writing [0-9] to match digits or [ \t\n\r] for whitespace, Java regex offers convenient shortcuts called predefined character classes. These are backslash-escaped letters that represent commonly used character sets.

The Big Three (and Their Negations)

\d - Digit Character

Matches any digit: 0-9. Equivalent to [0-9].

\w - Word Character

Matches letters, digits, and underscore: [a-zA-Z0-9_]. Think of it as "characters valid in identifiers."

\s - Whitespace Character

Matches spaces, tabs, newlines, and other whitespace characters.

Negated Forms

Each has an uppercase counterpart that matches the opposite:

  • \D - anything that's NOT a digit
  • \W - anything that's NOT a word character
  • \S - anything that's NOT whitespace

Practical Examples

Pattern digitPattern = Pattern.compile("\\d+");
// Matches: "123", "007"

Pattern wordPattern = Pattern.compile("\\w+");
// Matches: "hello", "user_123", "Test99"

Pattern whitespacePattern = Pattern.compile("\\s+");
// Matches: " ", "  \t\n"

Pattern nonDigit = Pattern.compile("\\D+");
// Matches: "abc", "hello world" (everything except digits)

Remember: In Java strings, you must escape the backslash, so \d becomes "\\d".

Analogy

Think of these as keyboard shortcuts. Instead of manually typing out [0-9] every time, \d is your Ctrl+C—a quick way to express the same thing with less typing and clearer intent.

Key Takeaway: Predefined character classes (\d, \w, \s) and their negated forms (\D, \W, \S) provide concise shortcuts for matching common character categories, making regex patterns more readable and maintainable.