Memra

Regular expressions: Pattern, Matcher & split

Regex syntax, capturing groups, matches vs find, and the Pattern/Matcher workflow.

Regular expressions in Java

A regular expression describes a pattern of characters. Java's regex engine lives in java.util.regex: you compile a pattern into a Pattern, then create a Matcher to apply it to input text. Some String methods (matches, replaceAll, split) wrap this for you.

Common metacharacters: . any char, \d a digit, \w a word char [a-zA-Z0-9_], \s whitespace, + one-or-more, * zero-or-more, ? optional, ^/$ start/end of input, [...] a character class, (...) a capturing group, | alternation.

> Java strings need the backslash itself escaped, so the regex \d is written "\\d" in source.

matches vs find

- matcher.matches() requires the entire input to match the pattern. - matcher.find() searches for the next substring that matches, and can be called repeatedly to walk all matches.

String.matches(regex) is whole-string, equivalent to Pattern.matches.

Capturing groups

Parentheses define groups, numbered left-to-right starting at group 1 (group 0 is the whole match). After a successful matches() or find(), matcher.group(n) returns the text the n-th group captured.

Worked example — parse a Greenhouse event line. The project reads lines like Event=LightOn,time=2000. We capture the event name and the time:

import java.util.regex.*;

String line = "Event=LightOn,time=2000";
Pattern p = Pattern.compile("Event=(\\w+),time=(\\d+)");
Matcher m = p.matcher(line);
if (m.matches()) {
    String name = m.group(1);            // "LightOn"
    long time = Long.parseLong(m.group(2)); // 2000
}

Step by step: Event= and ,time= are literal text; (\\w+) captures LightOn as group 1; (\\d+) captures the digits 2000 as group 2. m.matches() succeeds because the pattern describes the *whole* line. Long.parseLong then turns the captured digit string into a number.

Splitting

String.split(regex) breaks a string on a delimiter pattern, returning a String[]:

String[] parts = "a,b,,c".split(",");   // ["a", "b", "", "c"]

Note the empty string between the two commas is preserved (trailing empties are dropped unless you pass a negative limit).

NORMAL ~/memra/learn/comp-308/regex-pattern-matcher utf-8 LF