Java Regex Split, Replace and Flags: splitWithDelimiters, replaceAll and Pattern Flags
Split and rewrite text with Java regular expressions: split limits and empty strings, splitAsStream, splitWithDelimiters, Scanner delimiters, replaceAll with $n and ${name}, quoteReplacement, replacement functions, appendReplacement, and every Pattern flag with its inline form.
kvi5hnuCode Sprout team member8 min readOn this page
The last regex article covers the remaining two uses of patterns: cutting a string into pieces at the places where a pattern matches, and replacing the matches with something else. It ends with the flags that change how a whole pattern behaves. This also closes Part 2 of the course.
Splitting
Often what you want is the text between the matches. Pattern.split returns it as an array, with the delimiters removed:
Pattern commas = Pattern.compile("\\s*,\\s*");
String[] tokens = commas.split("1, 2 , 3,4"); // ["1", "2", "3", "4"]
For many tokens, splitAsStream produces them lazily as a Stream<String>:
List<Integer> numbers = commas.splitAsStream(input).map(Integer::parseInt).toList();
Since Java 21, splitWithDelimiters also keeps the delimiters, alternating between tokens and the matched delimiters. That's useful when you need to rebuild the text or inspect what separated the parts:
commas.splitWithDelimiters("1, 2 , 3,4", 0); // ["1", ", ", "2", " , ", "3", ",", "4"]
String has the same methods as shortcuts: input.split(regex), input.split(regex, limit) and input.splitWithDelimiters(regex, limit). They compile the regex on each call, except for a fast path for one ordinary character, or a backslash plus one character, which needs no regex engine at all. For repeated use, keep a compiled Pattern.
The limit and empty strings
The optional limit argument controls how many times the pattern is applied and what happens to empty strings:
limit | Effect | "a,b,,c,,".split(",", limit) |
|---|---|---|
0 (the default) | split everywhere, then drop trailing empty strings | ["a", "b", "", "c"] |
| negative | split everywhere, keep everything | ["a", "b", "", "c", "", ""] |
| positive n | at most n elements; the last holds the unsplit rest | with 2: ["a", "b,,c,,"] |
Other rules worth knowing:
- Empty strings between delimiters are always kept.
- A delimiter at the very start produces a leading empty string:
",a,b".split(",")is["", "a", "b"]. But a zero-width match at the start doesn't (since Java 8). So"CamelCaseString".split("(?=\\p{Lu})")gives["Camel", "Case", "String"]. - Splitting an empty string gives an array with one empty string,
[""], not an empty array. - To keep trailing empty fields, as in CSV data, pass
-1.
Splitting input from a file
A Scanner splits its input on a delimiter pattern, which is white space by default. Change it with useDelimiter, then read tokens one at a time or as a stream with tokens():
try (var in = new Scanner(path, StandardCharsets.UTF_8)) {
in.useDelimiter("\\s*;\\s*");
List<String> values = in.tokens().toList();
}
Replacing
Matcher.replaceAll replaces every match and returns the new string. replaceFirst replaces only the first match. String has the same two methods taking a regex.
String normalized = commas.matcher(input).replaceAll(","); // "1,2,3,4"
String same = input.replaceAll("\\s*,\\s*", ",");
Group references in the replacement
The replacement string isn't purely literal. $n inserts the text of group n, and ${name} inserts a named group:
"3:45".replaceAll("(\\d{1,2}):(?<minutes>\\d{2})", "$1 hours and ${minutes} minutes");
// "3 hours and 45 minutes"
"2026-11-14".replaceFirst("(\\d+)-(\\d+)-(\\d+)", "$3.$2.$1"); // "14.11.2026"
Consequently, $ and \ are special in replacements. A replacement of "$9.99" fails at run time with IndexOutOfBoundsException: No group 9. Escape them as \$ and \\, or let Matcher.quoteReplacement(s) do it for any string that comes from data.
Computing the replacement
Since Java 9, replaceAll and replaceFirst also accept a Function<MatchResult, String>, which computes each replacement from the match:
Pattern.compile("\\pL{4,}").matcher("Mary had a little lamb")
.replaceAll(m -> m.group().toUpperCase()); // "MARY had a LITTLE LAMB"
The function's result is still interpreted as a replacement string, with $ and \ being special. Wrap computed text in Matcher.quoteReplacement unless you want group references, as the template example in the demo does.
For full control, for example to compute a running total while replacing, use the lower-level pair appendReplacement and appendTail:
var out = new StringBuilder();
while (m.find()) {
// inspect m.group(...), update state
m.appendReplacement(out, replacement); // copies the text before the match, then the replacement
}
m.appendTail(out); // copies the rest after the last match
The StringBuilder overloads were added in Java 9. Older code uses StringBuffer.
Flags
Flags change how the whole pattern, or part of it, is interpreted. Pass them to compile, combined with |:
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Most flags can also be written inside the pattern: (?im) turns flags on from that point, (?-i) turns them off, and (?i:X) applies them only to X. Inline flags are handy when the pattern is a configuration string, or when only part of it should be affected.
| Constant | Inline | Effect |
|---|---|---|
CASE_INSENSITIVE | i | ignore case, ASCII letters only by default |
UNICODE_CASE | u | with i, ignore case for all Unicode letters |
UNICODE_CHARACTER_CLASS | U | \w \d \s \b and POSIX classes follow Unicode; implies UNICODE_CASE |
MULTILINE | m | ^ and $ match at the start and end of every line |
DOTALL | s | . also matches line terminators |
UNIX_LINES | d | only \n counts as a line terminator for ., ^ and $ |
COMMENTS | x | ignore white space, and treat # to end of line as a comment |
LITERAL | none | the whole pattern is literal text; CASE_INSENSITIVE and UNICODE_CASE still apply |
CANON_EQ | none | canonically equivalent sequences match, so ü matches u + combining diaeresis |
Pattern.flags() returns the flags in effect for the pattern: those passed to compile, plus inline flags at the very start of the pattern such as a leading (?i). Scoped flags like (?i:X) aren't included.
Without MULTILINE, ^ and $ refer to the whole input, so ^java$ doesn't match inside a multi-line string. Without DOTALL, . stops at line ends, so Java.java can't span Java\njava. And CASE_INSENSITIVE on its own doesn't match σίσυφος against ΣΊΣΥΦΟΣ. It needs UNICODE_CASE too.
The program
The demo walks through each technique: splitting with all four limit modes and the common pitfalls, tokens from a temporary file, replacements with group references, quoting, functions and appendReplacement, and every flag on a small multi-line text.
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
static String show(String[] parts) {
var sb = new StringJoiner(", ", "[", "]");
for (String p : parts) sb.add('"' + p + '"');
return sb.toString();
}
public static void main(String[] args) throws Exception {
System.out.println("--- splitting ---");
String input = "1, 2 , 3,4";
Pattern commas = Pattern.compile("\\s*,\\s*");
System.out.println("split: " + show(commas.split(input)));
System.out.println("splitAsStream: " + commas.splitAsStream(input).map(Integer::parseInt).toList());
System.out.println("splitWithDelimiters:" + show(commas.splitWithDelimiters(input, 0)));
System.out.println("String.split: " + show(input.split("\\s*,\\s*")));
String csv = "a,b,,c,,";
for (int limit : new int[] {0, -1, 2, 10})
System.out.printf("\"%s\".split(\",\", %2d) = %s%n", csv, limit, show(csv.split(",", limit)));
System.out.println("leading delimiter: " + show(",a,b".split(",")));
System.out.println("zero-width split: " + show("CamelCaseString".split("(?=\\p{Lu})")));
System.out.println("split(\".\"): " + show("com.example.app".split(".")));
System.out.println("split(\"\\\\.\"): " + show("com.example.app".split("\\.")));
System.out.println("split(quote(\".\")): " + show("com.example.app".split(Pattern.quote("."))));
System.out.println("split(\"|\"): " + show("a|b".split("|")));
System.out.println("empty input: " + show("".split(",")));
Path file = Files.createTempFile("data", ".csv");
Files.writeString(file, "10 ; 20;30 ;\n40", StandardCharsets.UTF_8);
try (var in = new Scanner(file, StandardCharsets.UTF_8)) {
in.useDelimiter("\\s*;\\s*");
System.out.println("Scanner tokens: " + in.tokens().toList());
} finally {
Files.delete(file);
}
System.out.println("--- replacing ---");
System.out.println(commas.matcher(input).replaceAll(","));
System.out.println("3:45".replaceAll("(\\d{1,2}):(?<minutes>\\d{2})", "$1 hours and ${minutes} minutes"));
System.out.println("2026-11-14".replaceFirst("(\\d+)-(\\d+)-(\\d+)", "$3.$2.$1"));
String price = "$9.99";
try {
System.out.println("total: TOTAL".replaceAll("TOTAL", price));
} catch (IndexOutOfBoundsException e) {
System.out.println("unquoted $ in replacement: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
System.out.println("total: TOTAL".replaceAll("TOTAL", Matcher.quoteReplacement(price)));
System.out.println("total: TOTAL".replace("TOTAL", price) + " (String.replace is literal)");
String sentence = "Mary had a little lamb";
System.out.println(Pattern.compile("\\pL{4,}").matcher(sentence).replaceAll(m -> m.group().toUpperCase()));
Map<String, String> vars = Map.of("name", "Ada", "lang", "Java");
String template = "Hi ${name}, welcome to ${lang}! ${unknown} stays.";
System.out.println(Pattern.compile("\\$\\{(\\w+)\\}").matcher(template)
.replaceAll(m -> Matcher.quoteReplacement(vars.getOrDefault(m.group(1), m.group()))));
Matcher money = Pattern.compile("(\\d+)\\s*USD").matcher("5 USD, 12USD and 3 EUR");
var out = new StringBuilder();
int total = 0;
while (money.find()) {
int amount = Integer.parseInt(money.group(1));
total += amount;
money.appendReplacement(out, "\\$" + amount);
}
money.appendTail(out);
System.out.println(out + " (sum " + total + ")");
System.out.println("replaceFirst with function: "
+ Pattern.compile("\\d+").matcher("a1b22c333").replaceFirst(m -> "<" + m.group().length() + ">"));
System.out.println("--- flags ---");
String text = "Java\njava\nJAVA script\nΣΊΣΥΦΟΣ";
System.out.println("plain: " + count("^java$", 0, text));
System.out.println("MULTILINE: " + count("^java$", Pattern.MULTILINE, text));
System.out.println("MULTILINE|CASE_INSENSITIVE: " + count("^java$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE, text));
System.out.println("inline (?im): " + count("(?im)^java$", 0, text));
System.out.println("scoped (?i:j)ava: " + count("(?m)^(?i:j)ava$", 0, text));
System.out.println("CASE_INSENSITIVE on Greek: " + count("σίσυφος", Pattern.CASE_INSENSITIVE, text));
System.out.println("plus UNICODE_CASE (?iu): " + count("(?iu)σίσυφος", 0, text));
System.out.println("dot without DOTALL: " + count("Java.java", 0, text) + ", with (?s): " + count("(?s)Java.java", 0, text));
System.out.println("COMMENTS: " + count("j a v a # spaces are ignored", Pattern.COMMENTS, text));
System.out.println("LITERAL: " + Pattern.compile("a.b", Pattern.LITERAL).matcher("a.b axb").results().count());
String composed = "ü", decomposed = "ü";
System.out.println("ü vs u+¨: plain " + Pattern.matches(composed, decomposed)
+ ", CANON_EQ " + Pattern.compile(composed, Pattern.CANON_EQ).matcher(decomposed).matches());
System.out.println("UNIX_LINES: " + count("(?m)^b$", 0, "a\r\nb\r\n") + " vs " + count("(?md)^b$", 0, "a\r\nb\r\n"));
Pattern p = Pattern.compile("x", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
System.out.println("flags(): " + p.flags() + " = CASE_INSENSITIVE(" + Pattern.CASE_INSENSITIVE
+ ") + MULTILINE(" + Pattern.MULTILINE + ")");
}
static long count(String regex, int flags, String text) {
return Pattern.compile(regex, flags).matcher(text).results().count();
}
}
--- splitting ---
split: ["1", "2", "3", "4"]
splitAsStream: [1, 2, 3, 4]
splitWithDelimiters:["1", ", ", "2", " , ", "3", ",", "4"]
String.split: ["1", "2", "3", "4"]
"a,b,,c,,".split(",", 0) = ["a", "b", "", "c"]
"a,b,,c,,".split(",", -1) = ["a", "b", "", "c", "", ""]
"a,b,,c,,".split(",", 2) = ["a", "b,,c,,"]
"a,b,,c,,".split(",", 10) = ["a", "b", "", "c", "", ""]
leading delimiter: ["", "a", "b"]
zero-width split: ["Camel", "Case", "String"]
split("."): []
split("\\."): ["com", "example", "app"]
split(quote(".")): ["com", "example", "app"]
split("|"): ["a", "|", "b"]
empty input: [""]
Scanner tokens: [10, 20, 30, 40]
--- replacing ---
1,2,3,4
3 hours and 45 minutes
14.11.2026
unquoted $ in replacement: IndexOutOfBoundsException: No group 9
total: $9.99
total: $9.99 (String.replace is literal)
MARY had a LITTLE LAMB
Hi Ada, welcome to Java! ${unknown} stays.
$5, $12 and 3 EUR (sum 17)
replaceFirst with function: a<1>b22c333
--- flags ---
plain: 0
MULTILINE: 1
MULTILINE|CASE_INSENSITIVE: 2
inline (?im): 2
scoped (?i:j)ava: 2
CASE_INSENSITIVE on Greek: 0
plus UNICODE_CASE (?iu): 1
dot without DOTALL: 0, with (?s): 1
COMMENTS: 1
LITERAL: 1
ü vs u+¨: plain false, CANON_EQ true
UNIX_LINES: 1 vs 0
flags(): 10 = CASE_INSENSITIVE(2) + MULTILINE(8)
Common questions
How do I collapse multiple spaces into one, or remove all whitespace?
text.replaceAll("\\s+", " ") collapses whitespace runs, and text.replaceAll("\\s", "") removes all of it. Add strip() to remove leading and trailing space, which \\s+ would otherwise turn into a single space.
Why does " a b".split("\\s+") start with an empty string?
The leading whitespace is a delimiter at the start, which produces an empty first field. Strip the string first, text.strip().split("\\s+"), or use a Scanner or splitAsStream followed by filter(s -> !s.isEmpty()).
How do I split on several different delimiters?
Use a character class or alternation: split("[,;\\s]+") splits on commas, semicolons and whitespace, treating runs of them as one delimiter.
Is StringTokenizer still used?
It is a legacy class from Java 1.0 that only supports single delimiter characters and has no regex support. The documentation recommends split or java.util.regex instead, and Scanner for parsing input.
How do I replace text case-insensitively while keeping the case of each match?
Use a replacement function: Pattern.compile("java", Pattern.CASE_INSENSITIVE).matcher(text).replaceAll(r -> Character.isUpperCase(r.group().charAt(0)) ? "Kotlin" : "kotlin"). The function sees each actual match and can adapt the replacement.
API reference
| API | Purpose |
|---|---|
Pattern.split(input), split(input, limit) | tokens between matches |
Pattern.splitAsStream(input) | lazy stream of tokens |
Pattern.splitWithDelimiters(input, limit) | tokens and delimiters, alternating (Java 21) |
String.split(regex[, limit]), String.splitWithDelimiters(regex, limit) | convenience versions |
Scanner.useDelimiter(pattern), tokens() | split a file or stream lazily |
Matcher.replaceAll(String), replaceFirst(String) | replace with $n/${name} expansion |
Matcher.replaceAll(Function<MatchResult,String>), replaceFirst(Function) | computed replacements (Java 9) |
Matcher.quoteReplacement(s) | escape $ and \ for use as a literal replacement |
Matcher.appendReplacement(sb, repl), appendTail(sb) | step-by-step replacement |
String.replaceAll(regex, repl), replaceFirst(regex, repl) | regex replacement on strings |
String.replace(target, replacement) | literal replacement of all occurrences |
Pattern.compile(regex, flags), Pattern.flags() | compile with flags, read them back |
Summary
splitremoves the delimiters.splitAsStreamis lazy, andsplitWithDelimiters(Java 21) keeps the delimiters.- A limit of 0 drops trailing empty strings, a negative limit keeps them, and a positive limit caps the number of pieces.
- The argument of
String.splitis a regex. Escape.,|and the other metacharacters, or usePattern.quote. - In replacements,
$nand${name}insert groups, so quote data withMatcher.quoteReplacement. Replacement functions andappendReplacementhandle computed replacements. String.replaceis the literal, regex-free replacement.- Flags (
i u U m s d x, plusLITERALandCANON_EQ) can be passed tocompileor, except the last two, embedded in the pattern.
Practice Questions
What does "x;;y;".split(";") return, and how do you keep the empty last field?
["x", "", "y"]. The empty string between the two semicolons is kept, but the trailing empty string after the last ; is dropped because the default limit is 0. Call split(";", -1) to get ["x", "", "y", ""].
Swap first and last names in lines like Lovelace, Ada using one replaceAll call.
line.replaceAll("(\\w+),\\s*(\\w+)", "$2 $1") gives Ada Lovelace. With named groups: "(?<last>\\w+),\\s*(?<first>\\w+)" and the replacement "${first} ${last}".
A user-supplied string is inserted into a text with replaceAll and the program crashes for the input C:\temp. Why, and what's the fix?
In a replacement string, \ escapes the next character, and $ starts a group reference. C:\temp turns into C:temp, and input with $ can throw IndexOutOfBoundsException or IllegalArgumentException. Wrap the input in Matcher.quoteReplacement(...), or use String.replace if the target is literal too.
Which flags make ^ERROR.*$ find every error line in a log file read into one string, including lines that end with \r\n?
MULTILINE ((?m)) so that ^ and $ work per line. With Windows line endings $ already matches before \r\n, and . doesn't match \r, so no other flag is needed. Don't add DOTALL, or .* would run across line breaks to the last one in the file.
Why can't LITERAL and CANON_EQ be written as inline flags?
They change how the pattern text itself is parsed before any matching starts: LITERAL turns off all metacharacters, including the (?...) syntax that inline flags would need, and CANON_EQ rewrites the pattern into canonically equivalent alternatives during compilation. They have no inline letters and can only be passed to Pattern.compile.
Previous: Java Regex Matching: matches, find, Groups and Named Groups
Next: Introducing XML: Document Structure, Elements and Attributes
Related reading
- Java Regex Matching: matches, find, Groups and Named Groups
- Java Regular Expressions: Syntax, Character Classes and Quantifiers
- Java Serialization: readResolve, writeReplace, Versioning and Security
- Customizing Java Serialization: transient, readObject, writeObject and Externalizable
- The Java Serialization File Format: Handles, Class Descriptors and Fingerprints

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.