Regular Expressions

A regular expression describes a pattern of text. In Java you compile it into a Pattern and use a Matcher to test, search or extract. This page explains how the engine works, tours the syntax, compares matches, lookingAt and find, covers groups, flags and lookaround, shows a pattern whose run time explodes, and measures what precompiling saves.

Contents

How Java's regex engine works

java.util.regex, added in Java 1.4, is a backtracking engine. It walks through the pattern and the input together, and whenever the pattern offers a choice, such as how many characters .* should take or which branch of a|b to try, it picks one and remembers the alternatives. When it gets stuck, it goes back to the last choice and tries the next one. This makes features such as backreferences and lookaround possible, but it also means a badly written pattern can try an enormous number of combinations.

The API has two main classes with different roles:

  • Pattern is the compiled form of a regex. Compiling parses the pattern into a tree of nodes, which takes time, so a pattern used repeatedly should be compiled once. A Pattern is immutable and safe to share between threads.
  • Matcher applies a pattern to one input and holds the state of the search: the current position and the groups of the last match. It is not thread-safe, but it can be reused with reset.
Regex APIs and when they arrived
APISinceBest for
Pattern.compile, Matcher.matches, find, lookingAtJava 1.4Everything; compile once, match many times
String.matches, replaceAll, splitJava 1.4One-off use; they compile the pattern on every call
Named groups (?<name>...)Java 7Readable extraction
Pattern.asPredicate, splitAsStreamJava 8Streams and filters
Matcher.results(), replaceAll(Function)Java 9All matches as a stream; computed replacements
Pattern.asMatchPredicateJava 11Filtering by a whole-string match
Pattern.namedGroups(), Matcher.namedGroups()Java 20Listing a pattern's group names

Replacing text is covered on the replace page and splitting on the split page. Each example was compiled and run on JDK 21.

The syntax in one program

Each line of output applies one construct to the same sentence, which contains names, an underscore, integers, a decimal, a negative number and a date, so every construct has something to find. In Java source each backslash is doubled, so the regex \d is written "\\d"; the output shows the regex itself.

Java
import java.util.List;
import java.util.regex.Pattern;

public class SyntaxTour {

    public static void main(String[] args) {
        String text = "Ann: 42, Bob_7: 3.5, Zoe: -8 (2026-11-14)";
        show("\\d", text);                  // a digit
        show("\\d+", text);                 // one or more digits
        show("\\w+", text);                 // word characters: letters, digits, _
        show("[A-Z]\\w*", text);            // character class, then zero or more
        show("[^\\w\\s]", text);            // negated class: not word, not space
        show("-?\\d+(?:\\.\\d+)?", text);  // optional sign and optional fraction
        show("\\d{4}-\\d{2}-\\d{2}", text); // exact counts
        show("\\b\\w{3}\\b", text);         // \b: word boundary
        show("^\\w+", text);                // ^: start of input
        show("\\d+(?=\\))", text);          // lookahead: digits followed by )
        show("(?<=: )\\w+", text);          // lookbehind: after ": "
        show("Ann|Zoe", text);              // alternation
    }

    static void show(String regex, String text) {
        List<String> found = Pattern.compile(regex).matcher(text).results()
            .map(r -> r.group()).toList();
        System.out.printf("%-22s %s%n", regex, found);
    }
}

Output:

Output
\d                     [4, 2, 7, 3, 5, 8, 2, 0, 2, 6, 1, 1, 1, 4]
\d+                    [42, 7, 3, 5, 8, 2026, 11, 14]
\w+                    [Ann, 42, Bob_7, 3, 5, Zoe, 8, 2026, 11, 14]
[A-Z]\w*               [Ann, Bob_7, Zoe]
[^\w\s]                [:, ,, :, ., ,, :, -, (, -, -, )]
-?\d+(?:\.\d+)?        [42, 7, 3.5, -8, 2026, -11, -14]
\d{4}-\d{2}-\d{2}      [2026-11-14]
\b\w{3}\b              [Ann, Zoe]
^\w+                   [Ann]
\d+(?=\))              [14]
(?<=: )\w+             [42, 3]
Ann|Zoe                [Ann, Zoe]
Regex constructs used above
ConstructMeaning
\d, \w, \sA digit, a word character (letter, digit or _), whitespace; uppercase \D, \W, \S negate them
[A-Z], [^...]One character from a set or range; ^ first negates the set
*, +, ?, {n}, {n,m}Zero or more, one or more, optional, exactly n, between n and m
(...), (?:...)A capturing group, and a group that only groups
^, $, \bStart and end of input (or of a line with MULTILINE), and a word boundary
(?=...), (?<=...)Lookahead and lookbehind: check what follows or precedes without consuming it
a|bEither alternative, tried left to right
  • \w+ found Bob_7 as one word, because the underscore and digits are word characters, but split 3.5 into 3 and 5.
  • The number pattern -?\d+(?:\.\d+)? found 3.5 and -8 correctly, but also read the date as 2026, -11 and -14. A regex matches what you wrote, not what you meant; tests with awkward input catch this.
  • \b\w{3}\b found only Ann and Zoe: \b requires a boundary on both sides, so the three-letter start of Bob_7 does not count.
  • The lookahead found only 14, the digits right before ), and the lookbehind found the values after ": " without including the colon.

matches, lookingAt and find

The three ways of applying a pattern differ in how much of the input must match, and confusing them is the most common regex bug in Java. The sentence contains two numbers, but does not start or consist of one.

Java
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchVsFind {

    public static void main(String[] args) {
        Pattern digits = Pattern.compile("\\d+");
        String text = "Order 66 shipped in 3 boxes";

        System.out.println("matches():   " + digits.matcher(text).matches());   // whole input?
        System.out.println("lookingAt(): " + digits.matcher(text).lookingAt()); // at the start?
        System.out.println("find():      " + digits.matcher(text).find());      // anywhere?
        System.out.println("lookingAt() on \"66 boxes\": "
            + digits.matcher("66 boxes").lookingAt());

        Matcher m = digits.matcher(text);
        while (m.find()) {
            System.out.println("found \"" + m.group() + "\" at " + m.start() + ".." + m.end());
        }

        // Java 9+: all matches as a stream
        System.out.println("results(): "
            + digits.matcher(text).results().map(r -> r.group()).toList());

        // Predicates for filtering: asPredicate finds, asMatchPredicate (Java 11) matches
        List<String> inputs = List.of("123", "abc", "12a", "007");
        Predicate<String> containsDigits = digits.asPredicate();
        Predicate<String> allDigits = digits.asMatchPredicate();
        System.out.println("asPredicate:      " + inputs.stream().filter(containsDigits).toList());
        System.out.println("asMatchPredicate: " + inputs.stream().filter(allDigits).toList());

        // String.matches must match the whole string: a common surprise
        System.out.println("\"id 42\".matches(\"\\\\d+\")   = " + "id 42".matches("\\d+"));
        System.out.println("\"id 42\".matches(\".*\\\\d+\") = " + "id 42".matches(".*\\d+"));
    }
}

Output:

Output
matches():   false
lookingAt(): false
find():      true
lookingAt() on "66 boxes": true
found "66" at 6..8
found "3" at 20..21
results(): [66, 3]
asPredicate:      [123, 12a, 007]
asMatchPredicate: [123, 007]
"id 42".matches("\\d+")   = false
"id 42".matches(".*\\d+") = true
  • matches() succeeds only if the whole input matches, lookingAt() if the start does, and find() if any part does. Only find succeeded on the sentence; lookingAt succeeded on 66 boxes.
  • Each call to find() continues after the previous match, so a while (m.find()) loop visits every match. start() and end() give the half-open range of each one: 66 is at 6..8.
  • results() returns the matches as a Stream<MatchResult>, which replaces the loop when you only need the values.
  • asPredicate() uses find, so it kept 12a. asMatchPredicate() uses matches and kept only the all-digit strings. Choosing the wrong one silently lets invalid input through a validation filter.
  • String.matches always tests the whole string, so "id 42".matches("\\d+") is false. Adding .* makes it true, but Pattern.compile("\\d+").matcher(s).find() says what you mean.

Capturing groups

Groups extract parts of a match. The log format here has an optional user field in brackets, so the program can show what an unmatched group returns, along with greedy and lazy matching on HTML-like text.

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

public class Groups {

    // Named groups document what each part means
    static final Pattern LOG = Pattern.compile(
        "(?<date>\\d{4}-\\d{2}-\\d{2}) (?<level>INFO|WARN|ERROR)"
            + "(?: \\[(?<user>\\w+)])? (?<msg>.*)");

    public static void main(String[] args) {
        for (String line : new String[] {"2026-11-14 WARN [ann] disk 91% full",
                "2026-11-14 INFO started"}) {
            Matcher m = LOG.matcher(line);
            if (m.matches()) {
                System.out.printf("date=%s level=%s user=%s msg=%s%n", m.group("date"),
                    m.group("level"), m.group("user"), m.group("msg"));
            }
        }
        Matcher m = LOG.matcher("2026-11-14 WARN [ann] disk 91% full");
        m.matches();
        System.out.println("groupCount() = " + m.groupCount() + ", group(0) = " + m.group(0));
        System.out.println("level spans " + m.start("level") + ".." + m.end("level"));
        System.out.println("namedGroups() = " + new java.util.TreeMap<>(LOG.namedGroups()));

        // Asking for a group before a successful match throws
        try {
            LOG.matcher("bad").group(1);
        } catch (IllegalStateException e) {
            System.out.println("group() without a match: " + e.getMessage());
        }

        // Greedy vs lazy: .* takes as much as possible, .*? as little as possible
        String html = "<b>one</b> and <b>two</b>";
        Matcher greedy = Pattern.compile("<b>(.*)</b>").matcher(html);
        Matcher lazy = Pattern.compile("<b>(.*?)</b>").matcher(html);
        greedy.find();
        lazy.find();
        System.out.println("greedy: " + greedy.group(1));
        System.out.println("lazy:   " + lazy.group(1));
        Pattern negated = Pattern.compile("<b>([^<]*)</b>");
        System.out.println("negated class: "
            + negated.matcher(html).results().map(r -> r.group(1)).toList());

        // A repeated group keeps only its last repetition
        Matcher rep = Pattern.compile("(\\d)+").matcher("2026");
        rep.matches();
        System.out.println("(\\d)+ on 2026: group(1) = " + rep.group(1));

        // A backreference \1 repeats what group 1 matched
        Matcher doubled = Pattern.compile("\\b(\\w+) \\1\\b").matcher("the the cat sat sat down");
        while (doubled.find()) {
            System.out.println("doubled word: " + doubled.group(1));
        }
    }
}

Output:

Output
date=2026-11-14 level=WARN user=ann msg=disk 91% full
date=2026-11-14 level=INFO user=null msg=started
groupCount() = 4, group(0) = 2026-11-14 WARN [ann] disk 91% full
level spans 11..15
namedGroups() = {date=1, level=2, msg=4, user=3}
group() without a match: No match found
greedy: one</b> and <b>two
lazy:   one
negated class: [one, two]
(\d)+ on 2026: group(1) = 6
doubled word: the
doubled word: sat
  • Named groups make the code read like the data. A group inside an optional part that did not take part in the match returns null, as user did for the second line, so check before using it.
  • Groups are numbered by their opening parenthesis from left to right, and (?:...) is not counted, so there are 4 groups. group(0) is the whole match. start("level") and end("level") give 11..15.
  • namedGroups(), new in Java 20, returns the map from names to numbers.
  • Calling group before a successful matches or find throws IllegalStateException with "No match found".
  • Greedy .* takes as much as possible and then backs off, so it matched from the first <b> to the last </b>. Lazy .*? takes as little as possible. A negated class such as [^<]* is usually better than either: it cannot run past the next tag, and it backtracks less.
  • A repeated group keeps only its last repetition, so (\d)+ on 2026 gives 6. To get every repetition, use find in a loop.
  • \1 refers back to what group 1 matched, which finds the two words written twice in a row.

Flags and Unicode

Flags change how the whole pattern is read. They can be passed to Pattern.compile or written inline at the start of the pattern, such as (?i). The inputs include accented letters, because several defaults are ASCII-only.

Java
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Flags {

    public static void main(String[] args) {
        // Case-insensitive, as a flag or inline; UNICODE_CASE for letters beyond ASCII
        System.out.println("CASE_INSENSITIVE JaVa:   "
            + Pattern.compile("java", Pattern.CASE_INSENSITIVE).matcher("JaVa").matches());
        System.out.println("(?i) on \u00C9T\u00C9 vs \u00E9t\u00E9:     "
            + "\u00C9T\u00C9".matches("(?i)\u00E9t\u00E9"));
        System.out.println("(?iu) on \u00C9T\u00C9 vs \u00E9t\u00E9:    "
            + "\u00C9T\u00C9".matches("(?iu)\u00E9t\u00E9"));

        // MULTILINE: ^ and $ match at every line, not just the ends of the input
        String lines = "id=1\nname=ann\nid=2";
        Pattern id = Pattern.compile("^id=(\\d+)$", Pattern.MULTILINE);
        System.out.println("MULTILINE ids: "
            + id.matcher(lines).results().map(r -> r.group(1)).toList());
        Pattern plain = Pattern.compile("^id=(\\d+)$");
        System.out.println("without:       "
            + plain.matcher(lines).results().map(r -> r.group(1)).toList());

        // DOTALL: . also matches newlines
        System.out.println("a.b on a\\nb without DOTALL: " + Pattern.matches("a.b", "a\nb"));
        System.out.println("a.b on a\\nb with (?s):      " + Pattern.matches("(?s)a.b", "a\nb"));

        // \w and \d are ASCII-only unless UNICODE_CHARACTER_CLASS is set
        String word = "na\u00EFve";
        System.out.println("\\w+ on na\u00EFve:     " + word.matches("\\w+"));
        System.out.println("(?U)\\w+ on na\u00EFve: " + word.matches("(?U)\\w+"));
        System.out.println("\\p{L}+ on na\u00EFve:  " + word.matches("\\p{L}+"));

        // COMMENTS: whitespace ignored and # starts a comment, for readable patterns
        Pattern date = Pattern.compile("""
            (\\d{4})  # year
            -(\\d{2}) # month
            -(\\d{2}) # day
            """, Pattern.COMMENTS);
        System.out.println("COMMENTS date: " + date.matcher("2026-11-14").matches());

        // Bad patterns fail when compiled, with the position of the error
        try {
            Pattern.compile("(unclosed");
        } catch (PatternSyntaxException e) {
            System.out.println("PatternSyntaxException: " + e.getDescription()
                + " near index " + e.getIndex());
        }
    }
}

Output:

Output
CASE_INSENSITIVE JaVa:   true
(?i) on ÉTÉ vs été:     false
(?iu) on ÉTÉ vs été:    true
MULTILINE ids: [1, 2]
without:       []
a.b on a\nb without DOTALL: false
a.b on a\nb with (?s):      true
\w+ on naïve:     false
(?U)\w+ on naïve: true
\p{L}+ on naïve:  true
COMMENTS date: true
PatternSyntaxException: Unclosed group near index 9
The most useful flags
FlagInlineEffect
CASE_INSENSITIVE(?i)Ignore case, for ASCII letters only
UNICODE_CASE(?u)With (?i), ignore case for all letters
MULTILINE(?m)^ and $ match at each line
DOTALL(?s). also matches line terminators
UNICODE_CHARACTER_CLASS(?U)\w, \d, \s and \b follow Unicode
COMMENTS(?x)Ignore whitespace and allow # comments
  • (?i) alone did not match ÉTÉ against été; adding u did.
  • Without MULTILINE, ^id=(\d+)$ found nothing in the three-line text, because ^ and $ refer to the whole input. With it, both ids were found.
  • \w+ rejected naïve, because \w means [a-zA-Z_0-9] by default. (?U)\w+ or the Unicode property \p{L} (any letter) accept it. This matters for validating names.
  • COMMENTS with a text block lets a long pattern be written over several lines with a comment per part.
  • A syntax error throws PatternSyntaxException at compile time, with a description and the index, here 9, the end of the pattern. Compiling patterns into static final fields makes such errors appear when the class loads, not deep inside a request.

Lookahead and lookbehind in practice

Lookaround checks a condition at a position without consuming characters, which lets one pattern test several independent rules. The examples are typical uses: a password policy, digit grouping, and extracting values next to a marker.

Java
import java.util.List;
import java.util.regex.Pattern;

public class Lookaround {

    // Each lookahead checks one rule from the start, without consuming characters
    static final Pattern PASSWORD = Pattern.compile(
        "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^\\w\\s]).{10,}$");

    public static void main(String[] args) {
        for (String pw : List.of("short1A!", "longenough1!", "LongEnough1!", "LongEnough12")) {
            System.out.printf("%-14s %s%n", pw, PASSWORD.matcher(pw).matches() ? "ok" : "rejected");
        }

        // Thousands separators: a position followed by groups of three digits up to the end
        System.out.println("1234567 -> " + "1234567".replaceAll("\\B(?=(\\d{3})+$)", ","));

        // Negative lookahead: words that are not followed by "Exception"
        String types = "IOException Reader TimeoutException Writer";
        System.out.println("not exceptions: " + Pattern.compile("\\b\\w+\\b(?<!Exception)")
            .matcher(types).results().map(r -> r.group()).toList());

        // Lookbehind: amounts after a currency sign, without the sign
        System.out.println("after $: " + Pattern.compile("(?<=\\$)\\d+(?:\\.\\d{2})?")
            .matcher("Paid $12.50, owed $7 and 9 points").results().map(r -> r.group()).toList());
    }
}

Output:

Output
short1A!       rejected
longenough1!   rejected
LongEnough1!   ok
LongEnough12   rejected
1234567 -> 1,234,567
not exceptions: [Reader, Writer]
after $: [12.50, 7]
  • The password pattern has four lookaheads at the start, one per rule: a digit, a lowercase letter, an uppercase letter, and a symbol. Each scans ahead and returns to the start, then .{10,} checks the length. longenough1! lacks an uppercase letter and LongEnough12 lacks a symbol.
  • \B(?=(\d{3})+$) matches the empty positions inside the number that are followed by a multiple of three digits, so replacing them with commas gives 1,234,567. For real formatting, NumberFormat is clearer; see numbers and strings.
  • The negative lookbehind (?<!Exception) after a word rejects words that end in Exception.
  • (?<=\$) found 12.50 and 7 after dollar signs, but not 9, and left the sign out of the match.

Catastrophic backtracking

Because the engine tries alternatives one by one, a pattern that can match the same text in many ways may take exponential time when the match finally fails. The input here is a run of a characters that is one short of what the pattern needs, so every attempt fails.

Java
public class Backtracking {

    public static void main(String[] args) {
        // Each .* can stop at any 'a', so the engine tries every way of splitting
        // the input into 21 pieces before giving up on the missing 21st 'a'
        for (int n : new int[] {16, 18, 20, 22, 24}) {
            String input = "a".repeat(n) + "!";
            time("(.*a){21}, n=" + n, () -> input.matches("(.*a){21}"));
        }
        String input = "a".repeat(24) + "!";
        time("[^a]*(a[^a]*){21}, n=24", () -> input.matches("[^a]*(a[^a]*){21}"));

        // Possessive quantifiers never give characters back, which can also prevent a match
        System.out.println("\"aaa\".matches(\"a*a\")  = " + "aaa".matches("a*a"));
        System.out.println("\"aaa\".matches(\"a*+a\") = " + "aaa".matches("a*+a"));

        // Deep recursion: alternation inside a repeated group uses stack per character
        String longText = "ab".repeat(20000);
        try {
            System.out.println("(a|b)* on 40,000 chars: " + longText.matches("(a|b)*"));
        } catch (StackOverflowError e) {
            System.out.println("(a|b)* on 40,000 chars: StackOverflowError");
        }
        System.out.println("[ab]* on 40,000 chars:  " + longText.matches("[ab]*"));
    }

    interface Check {
        boolean run();
    }

    static void time(String label, Check check) {
        long t0 = System.nanoTime();
        boolean matched = check.run();
        System.out.printf("%-26s matched=%b in %,8.1f ms%n", label, matched,
            (System.nanoTime() - t0) / 1e6);
    }
}

Output (single runs on a 2-CPU Linux machine, JDK 21; the growth matters, not the exact times):

Output
(.*a){21}, n=16            matched=false in     11.8 ms
(.*a){21}, n=18            matched=false in     15.6 ms
(.*a){21}, n=20            matched=false in     41.3 ms
(.*a){21}, n=22            matched=false in     86.6 ms
(.*a){21}, n=24            matched=false in    319.0 ms
[^a]*(a[^a]*){21}, n=24    matched=false in      0.5 ms
"aaa".matches("a*a")  = true
"aaa".matches("a*+a") = false
(a|b)* on 40,000 chars: StackOverflowError
[ab]* on 40,000 chars:  true
  • In (.*a){21}, each .* can stop before any of the a characters, so the number of ways to divide the input grows combinatorially. Every two extra characters made the failing match roughly two to four times slower. A few more characters, or a pattern like this applied to a long user-supplied string, can hang a thread for minutes: a regex denial-of-service, or ReDoS.
  • The unambiguous version, [^a]*(a[^a]*){21}, describes the same strings, but there is only one way to match each part, so it failed in well under a millisecond.
  • Possessive quantifiers such as *+ and atomic groups (?>...) never give characters back, which removes backtracking. They also change the meaning: a*+a cannot match aaa, because a*+ keeps all three letters.
  • Alternation inside a repeated group, (a|b)*, recurses once per repetition, and on 40,000 characters it threw StackOverflowError. The character class [ab]* matches the same input without recursion.

Rules of thumb: avoid nested quantifiers over the same characters, prefer character classes to alternation, and limit the length of untrusted input before matching it.

What precompiling saves

The program validates a million product codes such as ABC-1234, half of them invalid, with String.matches, a precompiled pattern, a reused matcher and a hand-written check. For each approach, the fastest of three runs is shown.

Java
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexSpeed {

    static final Pattern CODE = Pattern.compile("[A-Z]{3}-\\d{4}");

    public static void main(String[] args) {
        String[] inputs = new String[1000000];
        for (int i = 0; i < inputs.length; i++) {
            inputs[i] = (i % 2 == 0 ? "ABC-" : "AB1-") + (1000 + i % 9000);
        }
        time("String.matches", inputs, s -> s.matches("[A-Z]{3}-\\d{4}"));
        time("static final Pattern", inputs, s -> CODE.matcher(s).matches());
        Matcher reused = CODE.matcher("");
        time("reused Matcher.reset", inputs, s -> reused.reset(s).matches());
        time("hand-written check", inputs, RegexSpeed::check);
    }

    static boolean check(String s) {
        if (s.length() != 8 || s.charAt(3) != '-') {
            return false;
        }
        for (int i = 0; i < 8; i++) {
            char c = s.charAt(i);
            if (i < 3 && (c < 'A' || c > 'Z') || i > 3 && (c < '0' || c > '9')) {
                return false;
            }
        }
        return true;
    }

    // Best of 3 runs
    static void time(String name, String[] inputs, Predicate<String> p) {
        long best = Long.MAX_VALUE;
        int ok = 0;
        for (int run = 0; run < 3; run++) {
            ok = 0;
            long t0 = System.nanoTime();
            for (String s : inputs) {
                if (p.test(s)) {
                    ok++;
                }
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-22s %6.1f ms  %,d valid%n", name, best / 1e6, ok);
    }
}

Output (rough figures from a 2-CPU Linux machine running JDK 21):

Output
String.matches          191.7 ms  500,000 valid
static final Pattern     51.1 ms  500,000 valid
reused Matcher.reset     59.0 ms  500,000 valid
hand-written check       17.2 ms  500,000 valid
  • String.matches compiles the pattern on every call and was about four times slower than the same pattern compiled once into a static final field.
  • Reusing one Matcher with reset(input) saves creating a matcher per input, but it made little difference across runs, sometimes faster and sometimes slower. Creating a Matcher is cheap, and a shared one must stay on one thread.
  • A hand-written check for this simple format was faster still. For fixed formats in hot code that can be worth it; for anything more complex, a precompiled pattern is the better balance of speed and clarity.

Choosing the right regex API

Choosing a regex call
GoalUse
Does the whole string have this format?PATTERN.matcher(s).matches()
Does the string contain the pattern?PATTERN.matcher(s).find()
Every matchwhile (m.find()) or m.results()
Parts of a matchNamed groups, checking optional groups for null
Filter a streamasMatchPredicate() for validation, asPredicate() for searching
Same pattern used repeatedlyA static final Pattern
Letters beyond ASCII\p{L}, or the (?U) and (?iu) flags
Untrusted input or long stringsUnambiguous patterns, character classes, and a length limit
Text with user-supplied partsPattern.quote for the literal parts