STRING INSTANCE METHODS

Java String splitWithDelimiters() method

splitWithDelimiters() splits text using a regex and returns a String[] array containing the text parts and the matched delimiters. The original string is unchanged.

Available since Java 21. Java 8, 11 and 17 do not have this method.

Text parts together with their delimiters

String tekstas = "Java-Quest-21";
String[] dalys = tekstas.splitWithDelimiters("-", 0);

System.out.println(dalys.length);
for (String dalis : dalys) {
  System.out.println("[" + dalis + "]");
}
Console output

5
[Java]
[-]
[Quest]
[-]
[21]

  1. Two hyphens divide the input into three text parts, and both delimiters are retained.
  2. dalys[0] is the first word, dalys[1] is the first delimiter, and dalys[2] is the second word.
  3. The result contains five elements. The loop prints each one in brackets so the delimiters are easy to identify.
  4. A zero limit lets this example use all delimiter matches. Trailing empty elements are explained separately.

The result is an array. Display its contents with a loop or Arrays.toString().

Calling the method and saving its result

splitWithDelimiters() is an instance method: call it on the string to split, passing the regex and limit as two arguments.

String[] dalys = tekstas.splitWithDelimiters("-", 0);

The variable to the left of the dot tekstas is the value being split. This is not a static call on the class name.

String tekstas = "Java:Quest";
String[] dalys = tekstas.splitWithDelimiters(":", 0);

System.out.println(dalys[0]);
System.out.println(dalys[1]);
System.out.println(dalys[2]);
System.out.println(tekstas);
Console output

Java
:
Quest
Java:Quest

The delimiter occupies its own element at index 1. The last line shows that the original string is unchanged. Always check array indexes against its length.

Method syntax and Java version

public String[] splitWithDelimiters(String regex, int limit)

Parts of splitWithDelimiters()
PartMeaning
regexA regular expression describing what counts as a delimiter. Its type is String, rather than char.
limitAn integer controlling how matches are used and how trailing empty elements are handled.
Return typeString[] — an array of text parts and matched delimiters in their original order.
Java versionJava 21+
Possible errorsPatternSyntaxException, NullPointerException

Both arguments are required. Unlike split(), this method has no one-argument overload. Zero and negative limits are valid values.

Different delimiters and multi-character matches

import java.util.Arrays;

String tekstas = "Java;Quest|21";
String[] dalys = tekstas.splitWithDelimiters("[;|]", 0);

System.out.println(Arrays.toString(dalys));
Console output

[Java, ;, Quest, |, 21]

The character class [;|] matches a semicolon or vertical bar. The array retains the actual matched character, so both different delimiters remain visible.

import java.util.Arrays;

String tekstas = "Java---Quest--21";

System.out.println(Arrays.toString(tekstas.splitWithDelimiters("-+", 0)));
Console output

[Java, ---, Quest, --, 21]

The regex -+ treats one or more consecutive hyphens as one match. The result retains the whole matched run, not the regex text or just one hyphen.

Literal delimiters: a dot and Pattern.quote()

import java.util.Arrays;

String tekstas = "java.quest.org";
String[] dalys = tekstas.splitWithDelimiters("\\.", 0);

System.out.println(Arrays.toString(dalys));
Console output

[java, ., quest, ., org]

A literal dot is written in a regex as \.. A Java string literal needs two backslashes: "\\.". An unescaped dot would be a regex construct rather than just the separator between these domain parts.

import java.util.Arrays;
import java.util.regex.Pattern;

String tekstas = "Java|Quest|21";
String skirtukas = "|";

String[] dalys = tekstas.splitWithDelimiters(Pattern.quote(skirtukas), 0);
System.out.println(Arrays.toString(dalys));
Console output

[Java, |, Quest, |, 21]

Pattern.quote(skirtukas) lets you use the variable contents as a literal delimiter. This is useful for regex metacharacters and multi-character separators. Outside a character class, the vertical bar has a special regex meaning.

How does limit control the result?

Limits when splitting with delimiters
ConditionBehavior
limit > 0Use at most limit - 1 delimiter matches; the total number of elements is at most 2 * limit - 1.
limit = 0Use all matches, but discard empty elements at the end of the result.
limit < 0Use all matches and retain trailing empty elements.

Here, a positive limit is not the maximum array length as it is for split(). Each used match can contribute both a text part and a delimiter. The bound is a maximum, not a promise of an exact element count.

A positive limit and the unsplit remainder

import java.util.Arrays;

String tekstas = "key=Java=Quest";

System.out.println(Arrays.toString(tekstas.splitWithDelimiters("=", 2)));
System.out.println(Arrays.toString(tekstas.splitWithDelimiters("=", 1)));
System.out.println(Arrays.toString(tekstas.splitWithDelimiters("=", 3)));
Console output

[key, =, Java=Quest]
[key=Java=Quest]
[key, =, Java, =, Quest]

  1. A limit of 2 uses one equals-sign match. It produces a part, the delimiter and the whole remaining input: three elements.
  2. A limit of 1 keeps the whole input in one element. This is not an error.
  3. A limit of 3 allows two matches, producing five elements for this input.

The final element can still contain separators: a positive limit stops further splitting and keeps the remainder intact.

Zero and negative limits: trailing empty parts

String tekstas = "Java,,";
String[] paprastos = tekstas.split(",", 0);
String[] nulineRiba = tekstas.splitWithDelimiters(",", 0);
String[] visos = tekstas.splitWithDelimiters(",", -1);

System.out.println(paprastos.length);
System.out.println(nulineRiba.length);
System.out.println(visos.length);
for (String dalis : visos) {
  System.out.println("[" + dalis + "]");
}
Console output

1
4
5
[Java]
[,]
[]
[,]
[]

The first number is the ordinary split() result length. The next two numbers show the delimiter-retaining lengths: four with zero and five with a negative limit.

Zero discards only trailing empty elements. Commas are not empty strings, so the final comma remains even when the empty part after it is removed.

Any negative limit preserves trailing empty elements. It does not mean counting elements backwards. The brackets [] in this loop output mark one empty string.

Leading and adjacent delimiters

String[] dalys = ",Java,,Quest,".splitWithDelimiters(",", -1);

System.out.println(dalys.length);
for (String dalis : dalys) {
  System.out.println("[" + dalis + "]");
}
Console output

9
[]
[,]
[Java]
[,]
[]
[,]
[Quest]
[,]
[]

The leading comma is a real one-character match: an empty text part is recorded before it, followed by the comma itself. Another empty part occurs between adjacent commas.

Four commas and five text parts produce nine elements. The negative limit also preserves the final empty part. Changing the regex to ",+" would group adjacent commas into one match, changing the array structure.

When the input contains only delimiters

String tekstas = ",,";
String[] dalys = tekstas.splitWithDelimiters(",", 0);

System.out.println(tekstas.split(",", 0).length);
System.out.println(dalys.length);
for (String dalis : dalys) {
  System.out.println("[" + dalis + "]");
}
Console output

0
4
[]
[,]
[]
[,]

Ordinary splitting with zero leaves an empty array here. The delimiter-retaining method keeps both commas and the empty parts before them; only the final empty part is discarded.

You therefore cannot infer this result solely from how split() behaves with a zero limit on the same input.

Empty input and a pattern with no match

String[] pirma = "Java".splitWithDelimiters(":", 0);
String[] antra = "".splitWithDelimiters(":", 0);
String[] trecia = "".splitWithDelimiters("", 0);

System.out.println(pirma.length);
System.out.println("[" + pirma[0] + "]");
System.out.println(antra.length);
System.out.println("[" + antra[0] + "]");
System.out.println(trecia.length);
Console output

1
[Java]
1
[]
1

When no delimiter is found, the original input remains in one element. Empty input with the colon pattern also returns one element: an empty string. An empty regex on empty input gives the same length in this example.

An array containing one empty string is different from an empty array. When the display is ambiguous, also check its length.

Zero-width matches at the start and inside the input

import java.util.Arrays;

String tekstas = "Java:Quest";
String[] pradzia = tekstas.splitWithDelimiters("(?=J)", -1);
String[] vidurys = tekstas.splitWithDelimiters("(?=:)", -1);

System.out.println(Arrays.toString(pradzia));
System.out.println(vidurys.length);
for (String dalis : vidurys) {
  System.out.println("[" + dalis + "]");
}
Console output

[Java:Quest]
3
[Java]
[]
[:Quest]

The pattern (?=J) checks the position before J without consuming the letter. Such a zero-width match at the very start adds neither an empty leading part nor an empty delimiter.

The pattern (?=:) finds a position before the colon inside the input. This time the array includes an empty delimiter, while the colon remains at the start of the next part: the regex match did not consume it.

This differs from a real comma or hyphen at the beginning. Here a delimiter can be an empty match, not just a visible character.

An empty regex also creates empty delimiters

import java.util.Arrays;

String tekstas = "Java";
String[] nulineRiba = tekstas.splitWithDelimiters("", 0);
String[] neigiamaRiba = tekstas.splitWithDelimiters("", -1);

System.out.println(nulineRiba.length);
System.out.println(Arrays.toString(nulineRiba));
System.out.println(neigiamaRiba.length);
Console output

7
[J, , a, , v, , a]
9

With zero, the result contains four letters and three empty delimiters between them. Two empty elements at the end are removed. A negative limit retains them, increasing the length to nine.

An empty regex is not a general way to obtain user-perceived Unicode characters. Emoji and combined characters can contain multiple UTF-16 units or code points.

Practical example: replace a word and preserve punctuation

String tekstas = "Java,  Quest;21";
String[] dalys = tekstas.splitWithDelimiters("[,;]\\s*", -1);

for (int i = 0; i < dalys.length; i += 2) {
  if (dalys[i].equals("Quest")) {
    dalys[i] = "Code";
  }
}

System.out.println(String.join("", dalys));
System.out.println(tekstas);
Console output

Java,  Code;21
Java,  Quest;21

  1. The regex [,;]\s* includes a comma or semicolon and following whitespace, including tabs and line breaks, in the delimiter match. Double the backslash in the Java literal.
  2. In this result, text parts occupy indexes 0, 2, 4. The loop checks only those entries and replaces the whole part Quest with Code.
  3. String.join("", dalys) joins the entries without inserting new separators. Both spaces after the comma stay in place.
  4. We changed an array element. The original String object is unchanged. The last line demonstrates this.

This example handles a simple agreed text format. Quoted CSV fields or a complex programming language require a parser for that format.

Comparison with split() and String.join()

import java.util.Arrays;

String tekstas = "Java:Quest";

System.out.println(Arrays.toString(tekstas.split(":", 0)));
System.out.println(Arrays.toString(tekstas.splitWithDelimiters(":", 0)));
Console output

[Java, Quest]
[Java, :, Quest]

split() is suitable when you only need the values. The method splitWithDelimiters() is suitable when punctuation, separator runs or formatting also matter.

Use an empty joining delimiter when reconstructing this result. Adding a comma or space while joining would insert new characters between the already retained entries.

split() · String.join()

Reusing one pattern for several strings

import java.util.Arrays;
import java.util.regex.Pattern;

Pattern taisykle = Pattern.compile("[;|]");

System.out.println(Arrays.toString(taisykle.splitWithDelimiters("Java;Quest", 0)));
System.out.println(Arrays.toString(taisykle.splitWithDelimiters("21|ready", 0)));
Console output

[Java, ;, Quest]
[21, |, ready]

Pattern.compile() prepares a pattern that can be used for several inputs. Here we call the method on this pattern: the first argument is the input text, while the regex is already stored in it.

This pattern splitting method was also added in Java 21. For one short string, calling the method directly on the string is often easier to read.

An invalid pattern: PatternSyntaxException

String tekstas = "Java,Quest";

String[] dalys = tekstas.splitWithDelimiters("[", 0);
System.out.println(dalys.length);
Result

PatternSyntaxException

The character [ starts a regex character class without closing it. Java throws PatternSyntaxException. The array assignment does not complete and the printing statement is not reached.

A null pattern and a null receiver

String tekstas = "Java,Quest";
String regex = null;

String[] dalys = tekstas.splitWithDelimiters(regex, 0);
System.out.println(dalys.length);
Result

NullPointerException

Here the input string exists, but the regex reference is null. That is different from an empty regex string.

String tekstas = null;

String[] dalys = tekstas.splitWithDelimiters(",", 0);
System.out.println(dalys.length);
Result

NullPointerException

This time there is no object on which to invoke the method. Both situations cause NullPointerException. They are two separate sources of error.

String tekstas = null;
String regex = ",";

if (tekstas != null && regex != null) {
  String[] dalys = tekstas.splitWithDelimiters(regex, 0);
  System.out.println(dalys.length);
} else {
  System.out.println(false);
}
Console output

false

This check guards only against null references. It does not validate regex syntax or make an invalid pattern valid.

Common mistakes

  • Omitting the second argument or treating the method as static.
  • Treating a positive limit as the maximum array length and forgetting the additional delimiter entries.
  • Assuming zero removes commas or every empty entry, although it removes only trailing empty entries.
  • Using regex metacharacters as literal separators without quoting or escaping them.
  • Mistaking a zero-width match for a consumed delimiter character.
  • Joining the array with additional separators and unintentionally changing the formatting.

When should you use splitWithDelimiters()?

Choose this method when you need to examine both the text parts and the matched delimiters: preserve punctuation, change selected parts or reconstruct simple text with its formatting.

When you only need field values, use split(). If you need match positions or capture groups, consider Matcher. Use a dedicated parser for a complex file format.