Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Regular expression syntax in Java

Read and write Java 21 regex patterns using character classes, quantifiers, groups, anchors, escapes, and inline flags.

Version: Java SE 21

Syntax

Regex: [A-Z], [^, ], \d, \., (X), (?:X), X?, X*, X+, X{n}, X{n,}, X{n,m}, ^, $, \A, \z, (?i)X, (?i:X)
Lesson pattern: (?i)password=[^, ]+
Java string literal: "\\A([A-Z]{2})-(\\d+)\\z"
Java API (assuming regex has at least one capturing group):
Matcher matcher = Pattern.compile(regex).matcher(input);
boolean wholeRegionMatches = matcher.matches();
matcher.reset();
if (matcher.find()) {
    String firstGroup = matcher.group(1);
}

Pattern.compile(regex) in java.util.regex compiles a pattern and throws PatternSyntaxException if the regex syntax is invalid. matcher(input) creates a Matcher: matches() checks the entire region (the whole input by default), while find() searches for the next matching substring.

Each of these regex character classes matches one character: [A-Z] matches an ASCII uppercase letter, and \d matches an ASCII digit by default. Quantifiers apply to the preceding item or group: ? means zero or one, * zero or more, + one or more, {n} exactly n, {n,} at least n, and {n,m} from n through m. (X) captures text; (?:X) groups without capturing. After a successful match, group(0) returns the whole match and group(1) returns the first capturing group's text if it participated.

The anchors mark positions without consuming characters. ^ and $ mark the start and end; (?m) also lets them match at line boundaries. $ can also match before a final line terminator. \A and \z mark the strict start and end of input with default region bounds. There are two layers of escapes: the regex \. matches a literal dot, and you write "\\d" in Java source to pass the regex \d to the engine.

The regular expression inline flag and negated class work together in (?i)password=[^, ]+. Inline (?i) enables ASCII case-insensitive matching from that point; (?i:X) limits it to X. A leading ^ inside the class negates it: [^, ] excludes only comma and ordinary space, not tabs or line breaks. + requires a nonempty value that stops at the first comma, space, or end of input. The pattern does not check the left boundary of the field name, so it is not a reliable way to redact secrets.

Examples

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexPatternsDemo {
    public static void main(String[] args) {
        Pattern id = Pattern.compile("\\A([A-Z]{2})-(\\d+)\\z");
        Matcher matcher = id.matcher("AB-204");
        if (matcher.matches()) {
            System.out.println("ID: " + matcher.group(1) + "/" + matcher.group(2));
        }

        Pattern field = Pattern.compile("(?i)password=[^, ]+");
        System.out.println("Field found: " + field.matcher("user=demo, PASSWORD=sample, role=test").find());
        System.out.println("Empty field found: " + field.matcher("user=demo, PASSWORD=, role=test").find());
    }
}

Result

ID: AB/204
Field found: true
Empty field found: false

The program reads two captures from `AB-204`, then uses `find()` on two sample strings to check for `PASSWORD=` followed by a nonempty value. It does not print the field value.

Related lessons

  • Java · Lesson 55 · Advanced · Version: 2
  • Java · Lesson 70 · Basic · Version: 2

Sources