skip to content

Character Classes

Bracketed sets with negation and ranges, the predefined \d, \w and \s shorthands, POSIX and Unicode property classes, and the dot that excludes line terminators. Interviewers use \d versus \p{Digit} to probe Unicode awareness.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What is a character class in a Java regular expression, and what does [abc] match?

level: juniorimportance: must knowfreq 78%

answer

  1. Square brackets = a SET of characters
  2. Matches exactly ONE character
  3. [abc] is not the word abc
  4. Add a quantifier (+, *) for many
  5. Most specials are literal inside [ ]

basics

~10 s

A character class is a set in square brackets that matches exactly ONE character from that set. [abc] matches a single 'a', 'b', or 'c' (not the word "abc").

solid answer

~40 s

A character class, written with square brackets, matches a single character chosen from the listed set. [abc] matches one character that is either 'a', 'b', or 'c'. It is not a sequence: to match the literal three-letter word you would write abc with no brackets. Inside a class, characters that are special elsewhere (like . or *) usually lose their special meaning, so [.] just matches a dot. A class always consumes exactly one input character; to match several you add a quantifier, e.g. [abc]+ matches one or more of those letters in a row. In Java you compile a pattern with Pattern.compile("[abc]") and apply it via a Matcher.

code

java · 8 lines
java
import java.util.regex.Pattern;

var oneOf = Pattern.compile("[abc]");
System.out.println(oneOf.matcher("a").matches());   // true  (one char, in set)
System.out.println(oneOf.matcher("abc").matches()); // false (three chars)

var run = Pattern.compile("[abc]+");
System.out.println(run.matcher("abc").matches());    // true  (+ = one or more)

go deeper

for a junior

Knows brackets define a set that matches one character and that [abc] is not the word abc.

for a middle

Explains that most metacharacters are literal inside a class and that quantifiers extend a class to many characters.

for a senior

Can contrast class semantics with alternation (a|b|c), discuss the few still-special chars inside a class, and reuse compiled Patterns.

for a principal

Frames character classes within overall pattern design, performance of reused Patterns, and when a class is clearer than alternation for maintainability.

## What a regular expression is A **regular expression** (regex) is a small text pattern describing a set of strings. Java exposes regex through two classes in `java.util.regex`: `Pattern` (a compiled pattern) and `Matcher` (applies the pattern to input). You write a pattern as a `String`, compile it with `Pattern.compile(...)`, then test text with `matcher(text).matches()` (whole string) or `.find()` (anywhere). ## What a character class is A **character class** is the part of a pattern written in square brackets `[...]`. It defines a **set of single characters**, and it matches **exactly one** character of the input — whichever input character is a member of the set. The word "class" here just means "set"; it has nothing to do with Java classes. - `[abc]` matches one character that is `a`, `b`, or `c`. - It does **not** match the three-letter string `abc`. That misreading is the single most common beginner mistake. To match the literal word you write `abc` (three ordinary characters, no brackets). ## One character only A class consumes **one** input character per match. If you want to match several characters from a set, you add a **quantifier** after the class: - `[abc]+` = one or more characters, each from the set (e.g. `cab`, `aaa`). - `[abc]*` = zero or more. - `[abc]{2,4}` = between two and four. ## Special characters inside a class Many characters that are special in the wider pattern (like `.`, `*`, `+`, `(`) are treated as **ordinary literals inside a class**. So `[.]` matches a literal dot, and `[*+]` matches a star or a plus. A few characters are still special inside a class — `]`, `^` (only at the start), `-` (between two chars forms a range), and `\` (escape) — and are covered by the other questions in this topic. ## Java specifics Because patterns are Java string literals, a backslash in the regex must be doubled in source. A plain class like `[abc]` needs no backslashes, but `[\d]` (digits) becomes `"[\\d]"` in Java source. Compile once and reuse the `Pattern`; it is immutable and thread-safe, whereas a `Matcher` is not. ## Deriving the answer Start from "brackets = a set", add "matches exactly one character", and you can explain `[abc]`, why it isn't the word `abc`, and why you need `+` to match runs.

  • How would you match the three-character literal string "abc"?
    Write the three characters with no brackets: the pattern abc. Brackets define a one-character set, so [abc] matches a single a, b, or c instead.
  • Why does [abc]+ match "cab" but [abc] does not?
    [abc] matches exactly one character. The + quantifier means "one or more", so [abc]+ matches a run of characters each drawn from the set, including "cab".

A character class is like a multiple-choice slot: the slot accepts exactly one answer, and the brackets list the acceptable answers. One slot, one pick.

saying these in an interview costs you the question

  • Thinking [abc] matches the literal word "abc"
  • Believing a class can match more than one character without a quantifier
  • Assuming you must escape . or * inside a class (usually unnecessary)

context

open as a page

What does the dot (.) match in Java regex, and how does it differ from a character class with respect to line terminators and the DOTALL flag?

level: middleimportance: must knowfreq 71%

basics

~20 s

By default the dot matches any single character EXCEPT a line terminator like \n. With the DOTALL flag it matches every character including newlines. A character class like [^x] matches newlines unless you exclude them.

open as a page

How do ranges [a-z] and negation [^abc] work in a Java character class, and how do you include a literal hyphen or caret?

level: middleimportance: must knowfreq 74%

basics

~20 s

[a-z] matches any one character whose code falls between 'a' and 'z'. [^abc] matches any one character that is NOT a, b, or c. Put a hyphen first or last (or escape it) to mean a literal dash.

open as a page

What do the predefined classes \d, \w, \s mean in Java regex, how do they relate to POSIX classes like \p{Alpha}, and what are their ASCII vs Unicode caveats?

level: middleimportance: should knowfreq 68%

basics

~10 s

\d is a digit, \w is a word character (letters, digits, underscore), \s is whitespace. Their uppercase forms (\D, \W, \S) are the negations. By default they match ASCII only unless you enable Unicode.

open as a page

How do class union and the Java-specific class intersection (&&) and subtraction work, e.g. [a-z&&[^aeiou]]?

level: seniorimportance: should knowfreq 42%

basics

~10 s

Listing members in a class unions them: [a-d[m-p]] is a..d or m..p. Java adds intersection with &&: [a-z&&[^aeiou]] means lowercase letters AND not a vowel, i.e. consonants. It is a set-difference trick.

open as a page