Examples · Java

Test a Java regular expression

Online regex testers use JavaScript's or PCRE's rules, which differ from Java's in small ways that matter. Testing in Java itself, with the same Pattern and the same escaping your code will use, removes the guesswork.

This pattern parses log lines into a level, a thread and a message with named groups. Every sample line goes in a table showing whether it matched and what each group captured.

The query

java-regex-tester.java · paste it into a Java tab and press F5, or run byterunner run java-regex-tester.java in a terminal

// Try a regular expression on some sample lines and see each match and its named groups.
var pattern = Pattern.compile("(?<level>INFO|WARN|ERROR) \\[(?<thread>[^\\]]+)\\] (?<message>.*)");

var lines = List.of(
    "INFO [main] Server started on port 8080",
    "WARN [pool-1] Slow query: 1840 ms",
    "debug line that should not match",
    "ERROR [http-3] Connection reset by peer");

record Match(String line, boolean matches, String level, String thread, String message) {}

var results = new ArrayList<Match>();
for (var line : lines) {
    var m = pattern.matcher(line);
    results.add(m.matches()
        ? new Match(line, true, m.group("level"), m.group("thread"), m.group("message"))
        : new Match(line, false, "", "", ""));
}
dump(results, "Matches");

What it shows

The output of that run, from byterunner run. In the app each table is a sortable grid.

Matches
line                                     matches  level  thread  message
---------------------------------------  -------  -----  ------  ---------------------------
INFO [main] Server started on port 8080  true     INFO   main    Server started on port 8080
WARN [pool-1] Slow query: 1840 ms        true     WARN   pool-1  Slow query: 1840 ms
debug line that should not match         false
ERROR [http-3] Connection reset by peer  true     ERROR  http-3  Connection reset by peer
(4 rows)

Change the pattern or add a line that ought to fail, and press F5. The backslashes are written as they would be in a Java string literal, so the pattern can be copied straight into your code.

m.find() in place of m.matches() looks for the pattern anywhere in the line instead of requiring the whole line to match.

Download ByteRunner Free for Windows and Linux. Getting started

More examples