I/O, Serialization & Networking
Regular Expressions
Pattern compiles a regex once; Matcher runs it. Java's flavor: doubled backslashes in string literals, named groups, and greedy-by-default quantifiers. Powerful, and famously easy to overuse.- Compile once, match many:
private static final Pattern P = Pattern.compile(...) matches= whole input;find= anywhere; anchors^ $ \bcontrol position- Named groups
(?<year>\d{4})beat numbered groups for readability - Greedy
*vs reluctant*?— the classic HTML-tag mismatch - Catastrophic backtracking: nested quantifiers can hang on crafted input
private static final Pattern DATE =
Pattern.compile("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})");
Matcher m = DATE.matcher(input);
if (m.matches()) { // entire input must match
int year = Integer.parseInt(m.group("year"));
}
while (m.find()) { // every occurrence
System.out.println(m.group());
}
String cleaned = input.replaceAll("\\s+", " ");
String[] cells = row.split("\\s*,\\s*");
List<String> words = DATE.splitAsStream(text).toList();In string literals every regex backslash doubles: the regex \d is written "\\d". Character classes [a-z], predefined \d \w \s (and negations \D \W \S), quantifiers * + ? {n,m}, alternation |, grouping (...), lookarounds (?=...) (?<=...). Flags like Pattern.CASE_INSENSITIVE or inline (?i).