Regular Expressions
A regular expression describes a text pattern. Java's Pattern class compiles that description, and a Matcher applies it to input.
matches requires the entire input to fit the pattern. find instead searches for a matching region inside larger text.
Find a code inside text
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String message = "Order 482 ships today";
Pattern digits = Pattern.compile("\\d+");
Matcher matcher = digits.matcher(message);
if (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Output:
482
find locates the first run of one or more digits inside the larger message. group returns the matched region.
Quantifiers control repetition. + means one or more, while braces set a count: \d{3} matches exactly three digits, and \d{2,4} matches two to four.
Match the whole input
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern year = Pattern.compile("\\d{4}");
System.out.println(year.matcher("2026").matches());
System.out.println(
year.matcher("Year 2026").matches());
System.out.println(
year.matcher("Year 2026").find());
}
}
Output:
true
false
true
\d{4} means exactly four digits. matches accepts "2026" but rejects "Year 2026", because the whole input must fit the pattern. find accepts "Year 2026" because four digits appear somewhere inside it.
Backslashes pass through Java string syntax before the regex engine sees them. A regex \d is written as "\\d" in Java source.
Complete the pattern for ROOM- followed by exactly three digits.