To split a string in Java, call text.split(regex); for example, "red,green,blue".split(",") returns three pieces. The argument is a regular expression, not always a plain-text delimiter, so escape special characters such as a dot. Use split(regex, limit) when you need to keep trailing empty fields or control how many pieces are returned.
What You’ll Need
- A Java development kit (JDK) and a place to write and run Java code, such as an IDE or a terminal.
- A string to split and a clear idea of what separates its fields: a comma, whitespace, a symbol, or another pattern.
- Basic familiarity with Java string literals and arrays. The examples use the standard
Stringclass and require no extra library.
Step-by-Step
- Choose the string and separator. Start by identifying the exact boundary between the pieces you want. For a comma-separated list, the text
"red,green,blue"has commas between its three values. Java’sString.splitmethod returns aString[]array, so decide whether an array is a suitable way to use the result. If you need to keep the original string, there is no special setup:splitcreates an array and does not alter the string. - Call
splitwith a regular expression. Put the delimiter pattern in the method call. A comma has no special meaning in regular expressions, so it can be passed directly. This complete example prints each piece:String text = "red,green,blue"; String[] parts = text.split(","); for (String part : parts) { System.out.println(part); }The output is
red,green, andblue, each on its own line. The method signature takes a regex, which is why some delimiters need extra care even though simple ones, such as a comma or colon, work as written. - Use a regex when the separator varies. A regular expression can represent a group of possible separators or repeated whitespace. For example,
"[,;]"matches either a comma or a semicolon, while"\\s+"matches one or more whitespace characters. In Java source, write the whitespace pattern as"\\s+": the Java string literal consumes one backslash, leaving\s+for the regex engine. Example:String line = "Ada Lin\t28"; String[] fields = line.split("\\s+");Here, three spaces and the tab each count as part of a whitespace run, so the result contains
Ada,Lin, and28. If your input can start or end with whitespace, consider trimming it first or otherwise deciding how those boundary spaces should be handled; a delimiter at the start can produce a leading empty field. - Escape regex metacharacters when you mean them literally. A dot in a regex means “any character,” not a period. In a Java string, escape the backslash as well, so use
"\\."to split on literal periods:String version = "17.0.2"; String[] numbers = version.split("\\.");The array contains
17,0, and2. Other regex metacharacters include|,*,+,?, parentheses, brackets, and backslashes. If a separator is a variable containing arbitrary literal text, usePattern.quoterather than trying to escape every possible character yourself:import java.util.regex.Pattern; String delimiter = "a+b"; String[] pieces = "lefta+bright".split(Pattern.quote(delimiter));This treats the entire value of
delimiteras ordinary text. - Choose a limit if empty fields matter. The one-argument form behaves as though its limit were zero: it discards empty strings at the end of the result. That can hide meaningful blank fields. Pass a negative limit to retain trailing empties:
String record = "name,age,,"; String[] columns = record.split(",", -1);This returns four elements:
name,age, an empty string, and another empty string. By contrast,record.split(",")drops the trailing empty elements. A positive limit controls the number of splits, not the maximum number of separators: for example,"id=42=extra".split("=", 2)returnsidand42=extra. The final array element contains the unsplit remainder. - Check and use the resulting array. Print the elements or inspect
parts.lengthwhile developing. Access an element with an index such asparts[0], remembering that Java arrays start at zero and that the number of pieces may differ from what you expect. If you need to process every item, a loop is safer than assuming a fixed number of fields. Also consider validating the field count before reading a particular position, especially when the string comes from a file, user input, or a network request.
Common Mistakes
- Passing a special character without escaping it. Calling
text.split(".")does not mean “split on periods”; the dot matches any character. Use"\\."for a literal dot. A bare pipe is also special: use"\\|"to split on the pipe character. - Forgetting that Java strings and regexes both use backslashes. The regex for a literal period is
\., but the Java source code must represent that backslash as"\\.". If the compiler reports an illegal escape, check the Java string literal. If the program compiles but splits incorrectly, check the regex meaning too. - Dropping trailing empty fields unintentionally. The default call removes empty strings at the end of the array. For records where blank final columns matter, use a negative limit, typically
split(delimiter, -1). - Assuming split understands quoted CSV data. Splitting
"red,\"dark, red\",blue"on commas also splits inside the quoted value.splitis not a CSV parser. Use a CSV library when the input follows CSV quoting and escaping rules. - Assuming the delimiter will always match. When no delimiter matches, the result is a one-element array containing the original string. Do not assume a successful split guarantees multiple fields.
Tips
- Use the simplest correct pattern. A literal comma needs only
","; use a regex character class such as"[,;]"only when either separator should count. - For general whitespace,
"\\s+"collapses a run into one boundary. If you need to preserve repeated spaces as meaningful empty fields, do not use that pattern; define a delimiter that matches the data format instead. - Use
split(regex, -1)for fixed-column records where blank final values must survive. Then validate the resulting array length before accessing expected columns. - If the same complex regex is used many times, compile it once with
Pattern.compileand use the pattern’ssplitmethod. This can make the intent clearer and avoid repeatedly compiling the expression. - Test representative boundary cases: an ordinary input, adjacent delimiters, a delimiter at the end, no delimiter, and an empty field. These cases reveal most surprises in how the resulting array is shaped.
Troubleshooting
The string seems to split at every character. Check whether the pattern is a metacharacter such as . or |. Escape it for the regex, and then escape the backslash for the Java string literal. For example, use "\\." for a period.
Some expected columns are missing. Look for empty fields at the end of the input. The one-argument method discards trailing empty strings; retry with a negative limit, such as split(",", -1). Also inspect the input for extra or missing separators instead of trusting that every record has the same shape.
The result has only one element. Confirm that the pattern actually matches the separator in the input. A comma pattern will not match a semicolon, and a literal separator may differ because of spaces or capitalization. Print the original string and examine the exact characters; tabs and other whitespace can be hard to see.
The program throws an index error after splitting. An expression such as parts[2] fails if the array has fewer than three elements. Check parts.length first, and decide how to handle malformed or incomplete input. If whitespace at the beginning creates an unexpected empty element, trim the input when that is appropriate for your data, or adjust the regex to match the intended format.
Frequently Asked Questions
Does Java split take a string or a regex?
It takes a regular expression. Simple delimiters such as commas can be passed directly, but regex metacharacters need escaping when you want their literal meaning.
How do I split a string on whitespace?
Use text.split("\\s+") to treat one or more whitespace characters as a separator. If leading or trailing whitespace is possible, decide whether to trim it before splitting.
How can I keep empty fields at the end?
Use a negative limit, for example text.split(",", -1). The default one-argument form removes trailing empty strings.
How do I split on a pipe or a dot?
Escape the regex character and its backslash in the Java literal: use "\\|" for a pipe and "\\." for a dot.
Does split change the original string?
No. Java strings are immutable, and split returns a new array of strings. The original value remains unchanged.
Can I use split to read CSV files?
Not reliably when fields can contain quoted commas, quotes, or escaped line breaks. Use a CSV parser that follows the file’s format rather than splitting on commas alone.
Related
- Excell Battery Calgary: What to Know Before You Go
- X++ Enum Values in SQL: How Stored Numbers Work in D365
- How to Add Speaker Notes to Your PowerPoint Slides
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Split Cell Without Adding a Column?No—not into two independent values while keeping both inside the same Excel cell: one cell can contain only…
- How to Insert a Line in Word Using Your KeyboardTo insert a horizontal line in Microsoft Word with your keyboard, put the cursor in an empty paragraph,…
- Excel Find and Replace Preview: How to Check ChangesExcel for Microsoft 365 on Windows does not provide a separate preview screen for Replace All. To review…
- Excel Table Saw: Models, Safety, and Buying AdviceAn Excel table saw is a woodworking saw sold under the Excel name; it is not a Microsoft…
- Does Excel Goal Seek Automatically Update?No. Excel Goal Seek finds an input value that makes a formula reach a target, then leaves that…
- Excel Goal Seek vs Solver: Which Tool Should You Use?Use Goal Seek when you know the result you want from one formula and need Excel to find…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.