Regular expressions

A regular expression is a pattern for text, and Java keeps it in a Pattern and matches it with a Matcher. The Matcher can find one occurrence, walk all of them, and give back the groups a pattern names, which is how a log line becomes a record. The three programs below are the three jobs: find, replace, and parse.

Groups with a Matcher

A pattern in parentheses is a group, numbered from one in the order of the opening parenthesis. find moves to the next match and group(n) answers the part of it:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Groups { public static void main(String[] args) { Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})"); Matcher matcher = pattern.matcher("on 2026-11-20 and 2027-01-02"); while (matcher.find()) { System.out.println(matcher.group() + " year " + matcher.group(1) + " month " + matcher.group(2) + " day " + matcher.group(3) + " at " + matcher.start()); } Pattern named = Pattern.compile("(?<key>\\w+)=(?<value>\\w+)"); Matcher namedMatcher = named.matcher("name=Ada age=36"); while (namedMatcher.find()) { System.out.println(namedMatcher.group("key") + " -> " + namedMatcher.group("value")); } System.out.println("count: " + named.matcher("a=1 b=2 c=3").results().count()); } }

javac -Xlint:all Groups.java
java Groups

2026-11-20 year 2026 month 11 day 20 at 3
2027-01-02 year 2027 month 01 day 02 at 18
name -> Ada
age -> 36
count: 3

group() with no argument is the whole match, and start() is its index in the input: the first date begins at three, after on . The count at the end uses results(), which is a stream of the matches, so the loop and the stream give the same answer the two ways a program counts.

Named groups

(?<key>\w+) names a group instead of numbering it, and group("key") reads it. A pattern with five groups is where the names pay: a number is counted from the opening parenthesis and moves when a group is added, while a name does not.

The syntax is in the documentation of Pattern, which is long and worth keeping open: \d a digit, \w a letter, digit or underscore, \s whitespace, \S the opposite of \s, and the anchors ^ and $ for the start and the end of the input.

replaceAll and split

String.replaceAll takes a pattern and a replacement that may refer to a group as $1, and String.split takes a pattern as the separator. matches answers whether the whole text fits the pattern:

import java.util.Arrays; import java.util.regex.Pattern; public class Replace { public static void main(String[] args) { String text = "ada@example.com and grace@navy.mil"; System.out.println(text.replaceAll("(\\w+)@(\\w+)\\.(\\w+)", "$1 at $2 dot $3")); String csv = "a, b ,c , d"; System.out.println(Arrays.toString(csv.split("\\s*,\\s*"))); System.out.println(String.join("|", Pattern.compile("\\s*,\\s*").split(csv))); System.out.println("digits only: " + "abc123".matches("\\D*\\d+")); System.out.println("replace digits: " + "room 12 floor 3".replaceAll("\\d+", "#")); System.out.println("quoted: " + Pattern.quote("a.b")); System.out.println("literal dot: " + "a.b".matches("a\\.b") + " " + "axb".matches("a\\.b")); } }

javac -Xlint:all Replace.java
java Replace

ada at example dot com and grace at navy dot mil
[a, b, c, d]
a|b|c|d
digits only: true
replace digits: room # floor #
quoted: \Qa.b\E
literal dot: true false

The separator \s*,\s* eats the spaces around each comma, so the four fields arrive without them; a plain split on the comma would have left the spaces. The last two lines are the difference between a dot and an escaped dot: a dot matches any character, so a\.b is the pattern for a literal one, and Pattern.quote wraps any text into a pattern that matches only itself, which is what a text from a user needs.

A log line parsed

The whole lesson in one program: a pattern with five groups for date time level service: message, a record per match, a count per level and a list of the lines that did not match:

import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Log { record Entry(String date, String time, String level, String service, String message) { } static final Pattern LINE = Pattern.compile( "^(\\S+) (\\S+) (\\w+) (\\w+): (.*)$"); public static void main(String[] args) { List<String> lines = List.of( "2026-11-20 14:05:09 WARN billing: slow query", "2026-11-20 14:05:10 INFO web: GET /health 200", "2026-11-20 14:05:11 ERROR billing: payment failed", "this line is not a log entry"); List<Entry> entries = new ArrayList<>(); List<String> rejected = new ArrayList<>(); for (String line : lines) { Matcher matcher = LINE.matcher(line); if (matcher.matches()) { entries.add(new Entry(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5))); } else { rejected.add(line); } } for (Entry entry : entries) { System.out.println(entry.level() + " " + entry.service() + " " + entry.message()); } Map<String, Integer> byLevel = new TreeMap<>(); for (Entry entry : entries) { byLevel.merge(entry.level(), 1, Integer::sum); } System.out.println("levels: " + byLevel); System.out.println("rejected: " + rejected.size() + " [" + rejected.get(0) + "]"); System.out.println("first date: " + entries.get(0).date()); } }

javac -Xlint:all Log.java
java Log

WARN billing slow query
INFO web GET /health 200
ERROR billing payment failed
levels: {ERROR=1, INFO=1, WARN=1}
rejected: 1 [this line is not a log entry]
first date: 2026-11-20

The anchors make matches and the pattern agree on what a whole line is, and (.*)$ takes the rest of the line as the message, spaces and all. A line that does not match is rejected and reported rather than silently skipped, which is the same rule as the parser of lesson 103: a reader has to know that a line was not understood.

Rules for regular expressions

Compile the pattern once and keep it in a constant, because the compile costs more than the match and a pattern in a loop is a hidden expense. Anchor a pattern that must match a whole line, since find and matches are different questions. Use named groups for a pattern with more than two. Quote a text that is not a pattern, as Pattern.quote does. And keep the pattern simple enough to read in a week: a regular expression is a small language with no compiler to catch a mistake, and the one that parses a nested structure should be a parser.

The cost of a badly written expression is the catastrophic backtracking of a pattern with nested repetitions, which can take minutes on a short text. Nothing in the JDK limits that, so a pattern that comes from outside the program is a denial of service unless it is bounded. A log parser sits on a constant pattern the program wrote, which is the safe end of the range.

Exercises

  1. Write a pattern for a hexadecimal colour and print the three components of #1a2b3c.
  2. Replace every repeated space in a sentence with one space using a pattern.
  3. Parse the query part of a URL into a map of keys and values with a Matcher.
  4. Add a level to the log program that rejects a line and print its index.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Matcher.find do?

    Answer

    Moves to the next occurrence of the pattern and answers whether there is one

    find walks the occurrences one at a time, and matches asks about the whole input.

  2. How is a group referred to in a replacement text?

    Answer

    As $1 for the first group

    replaceAll reads $n in the replacement, while replaceFirst and the Matcher do the same.

  3. Why does Pattern.quote exist?

    Answer

    A text from a user may contain characters that are pattern syntax

    The quote wraps the text so that the pattern matches it literally.

  4. What does this program print? import java.util.regex.Matcher; import java.util.regex.Pattern; public class Q1 { public static void main(String[] args) { Matcher m = Pattern.compile("(a)(b)?").matcher("a ab"); int count = 0; while (m.find()) { count++; } System.out.println(count); System.out.println(Pattern.compile("(\\d+)").matcher("a1b22c333").results().count()); } }

    Answer

    2 / 3

    The first pattern matches a twice, and the second finds three runs of digits.

  5. Which anchors a pattern to the whole line?

    Answer

    A ^ at the start and a $ at the end

    The two anchors fix the position of the match at the ends of the input.

  6. What does String.matches answer?

    Answer

    Whether the whole string fits the pattern

    matches anchors the pattern itself, which is why a pattern for a part needs .* around it.

  7. Why should a compiled Pattern be a constant?

    Answer

    The compile costs more than a match, and a pattern in a loop pays it every time

    A Pattern is immutable and reusable, so one compile serves every line of the file.

  8. What does this program print? import java.util.regex.Pattern; public class Q2 { public static void main(String[] args) { System.out.println("a1b2".replaceAll("\\d", "#")); System.out.println("a1b2".split("\\d").length); } }

    Answer

    a#b# / 2

    Each digit is replaced, and split drops the empty part after the last digit, leaving two.

  9. What does this program print? import java.util.regex.Matcher; import java.util.regex.Pattern; public class Q3 { public static void main(String[] args) { Matcher m = Pattern.compile("(?<x>\\w+)=(?<y>\\d+)").matcher("a=1 b=22"); while (m.find()) { System.out.print(m.group("x") + m.group("y") + " "); } } }

    Answer

    a1 b22

    The two named groups are read by name and printed next to each other.

  10. What makes a regular expression dangerous on input from outside the program?

    Answer

    Catastrophic backtracking on some patterns can take minutes

    A nested repetition can explore an exponential number of ways, and nothing in the JDK bounds it.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev