All topics
library
intermediate

Regular Expressions in Java

Use Pattern and Matcher for regex operations and know the performance implications of compiled vs inline patterns.

Java regex uses java.util.regex.Pattern and Matcher. Patterns are compiled from regex strings and can be reused.

Compiling a Pattern = building a custom maze. Each Matcher call = running a mouse through the maze. Reusing the maze (Pattern) is fast; rebuilding it every time (String.matches) is slow.

Key Concepts

1
Key classes: - Pattern.compile(regex) — compiles a regex into a reusable Pattern - pattern.matcher(input) — creates a Matcher for an input string - matcher.matches() — does the entire string match? - matcher.find() — find next occurrence - matcher.group() — return the matched text - matcher.group(n) — return capture group n
2
Convenience methods: String.matches(regex), String.replaceAll(regex, replacement), String.split(regex). These compile the pattern every time — avoid in loops.
3
Common patterns: - \d digit, \w word char, \s whitespace - [a-z] character class, [^a-z] negation - . any char, * zero+, + one+, ? zero or one - ^ start, $ end - (group) capturing group, (?:group) non-capturing - (?<name>...) named group
4
Flags: Pattern.CASE_INSENSITIVE, Pattern.MULTILINE, Pattern.DOTALL.
5
Performance: compile patterns once and reuse (Pattern is thread-safe, Matcher is not). Avoid catastrophic backtracking with nested quantifiers like (a+)+.