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

Character Classes: [...] Basics

Create custom character sets with square brackets to match any single character from the defined set.

Character Classes: [...] Basics

What you'll learn: How to create custom character sets using square brackets to match any single character from your defined collection.

The Core Idea

A character class is a set of characters enclosed in square brackets [...]. It matches exactly one character from the set you define. Think of it as a menu: the regex engine looks at the next character in your string and asks, "Is this character on the menu?" If yes, it's a match.

For example, [aeiou] matches any single vowel. When the regex engine encounters this pattern, it will match a, e, i, o, or u — but only one character at a time.

Basic Syntax

Pattern pattern = Pattern.compile("[abc]");
Matcher matcher = pattern.matcher("cab");

while (matcher.find()) {
    System.out.println("Found: " + matcher.group());
}
// Output:
// Found: c
// Found: a
// Found: b

Here, [abc] means "match a single character that is either a, b, or c."

Common Examples

  • [0-9] — matches any single digit (range notation)
  • [A-Za-z] — matches any single letter (uppercase or lowercase)
  • [aeiouAEIOU] — matches any vowel, case-insensitive
  • [13579] — matches any odd single digit

Why This Matters

Character classes let you build flexible patterns without writing multiple alternatives. Instead of (a|e|i|o|u), you write the cleaner [aeiou]. They're essential for validation, parsing, and searching when you need "any character from this specific set."

Key Takeaway: Character classes [...] define a custom set of characters and match exactly one character from that set, making pattern matching concise and readable.