Regular Expressions in Java
A regular expression is a pattern describing a set of matching text, and Java supports them through the java.util.regex package: Pattern.matches(regex, input) checks whether an entire input matches a given pattern, and String itself offers convenient shortcuts like matches(regex), replaceAll(regex, replacement), and split(regex) that use regular expressions directly, without needing the Pattern class explicitly for simple cases. Common regex building blocks include a backslash followed by the letter d for any digit, a backslash followed by the letter w for any word character (a letter, digit, or underscore), a plus sign meaning one or more of whatever came right before it, and a question mark meaning zero or one.
Within a Java string literal, a backslash must be doubled to survive as one literal backslash in the resulting text, since the string literal's own escaping resolves before the regex engine ever sees the pattern at all. That's why a Java regex matching a run of digits is written with two backslash characters in the source, not one, even though the underlying regex itself only uses a single escape.
The core regex API
Pattern.matches(regex, input) checks a full match; String's own matches, replaceAll, and split methods use regular expressions directly for common cases.
Digit and word-character classes
A backslash followed by the letter d matches any single digit; a backslash followed by the letter w matches any word character — a letter, digit, or underscore.
Quantifiers
A plus sign means one or more of whatever came right before it; an asterisk means zero or more; a question mark means zero or one.
Doubled backslashes in Java source
A Java string literal needs two backslash characters to represent one literal backslash in the resulting text, since the string literal's escaping resolves before the regex engine ever reads the pattern.
replaceAll and split both take a full regex
Not just a literal substring — a period inside either one means any character, not a literal dot, unless it's itself escaped.
import java.util.regex.Pattern; public class RegexDemo { public static void main(String[] args) { String input = "Room 42B"; boolean hasDigits = Pattern.matches(".*\\d+.*", input); String digitsOnly = input.replaceAll("\\D", ""); System.out.println("Has digits: " + hasDigits); System.out.println("Digits only: " + digitsOnly); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.