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

Character Ranges: [a-z], [0-9], [A-Z]

Define contiguous character ranges efficiently using the hyphen notation within character classes.

Character Ranges: [a-z], [0-9], [A-Z]

You'll learn how to define contiguous character ranges efficiently using the hyphen notation within character classes.

The Core Idea

Instead of writing out every single character you want to match in a character class, you can use the hyphen (-) notation to specify a contiguous range of characters. This makes your regex patterns much more compact and readable.

For example, instead of writing [abcdefghijklmnopqrstuvwxyz] to match any lowercase letter, you can simply write [a-z]. The hyphen tells the regex engine "match any character from 'a' through 'z' in Unicode order."

Common Character Ranges

Here are the most frequently used ranges:

  • [a-z] — Matches any lowercase letter (a through z)
  • [A-Z] — Matches any uppercase letter (A through Z)
  • [0-9] — Matches any digit (0 through 9)

You can also combine multiple ranges in a single character class:

  • [a-zA-Z] — Matches any letter (lowercase or uppercase)
  • [a-zA-Z0-9] — Matches any letter or digit
  • [0-9a-f] — Matches hexadecimal digits (0-9 and a-f)

Think of It Like a Shortcut

Imagine you're listing items from a shelf numbered 1 through 50. Instead of saying "1, 2, 3, 4... 50," you'd say "1 through 50." Character ranges work the same way—they're a shorthand for "all characters between these two endpoints."

Pattern p = Pattern.compile("[a-z]+");
Matcher m = p.matcher("hello123WORLD");
if (m.find()) {
    System.out.println(m.group()); // Outputs: hello
}

Key Takeaway: Use the hyphen (-) inside character classes to define contiguous ranges like [a-z], [0-9], or [A-Z], making your patterns concise and readable while matching all characters within the specified range.