Use the appropriately named method String#split().

Use with AIString string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

Use with AIString[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

To test beforehand if the string contains certain character(s), just use String#contains().

Use with AIif (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

Use with AIString string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

Use with AIString string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

Use with AIString string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
Answer from BalusC on Stack Overflow
🌐
W3Schools
w3schools.com › java › ref_string_split.asp
Java String split() Method
The split() method splits a string into an array of substrings using a regular expression as the separator. If a limit is specified, the returned array will not be longer than the limit.
🌐
GeeksforGeeks
geeksforgeeks.org › java › split-string-java-examples
Java String split() Method - GeeksforGeeks
May 13, 2026 - The split() method in Java is used to divide a string into multiple parts based on a specified delimiter (regular expression). It returns an array of substrings after splitting the original string.
🌐
IronPDF
ironpdf.com › ironpdf for java › ironpdf for java blog › java pdf tools › string.split java
String.split Java (How It Works For Developers)
August 2, 2026 - When utilizing this method, developers can define a regular expression pattern using string regex or a simple character as the delimiter to split a given string. Java String split() method is public and static, often found within the main method of a Java program, where the string args parameter can be employed for command-line input.
Top answer
1 of 16
3416

Use the appropriately named method String#split().

Use with AIString string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

Use with AIString[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

To test beforehand if the string contains certain character(s), just use String#contains().

Use with AIif (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

Use with AIString string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

Use with AIString string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

Use with AIString string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
2 of 16
91

An alternative to processing the string directly would be to use a regular expression with capturing groups. This has the advantage that it makes it straightforward to imply more sophisticated constraints on the input. For example, the following splits the string into two parts, and ensures that both consist only of digits:

Use with AIimport java.util.regex.Pattern;
import java.util.regex.Matcher;

class SplitExample
{
    private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");

    public static void checkString(String s)
    {
        Matcher m = twopart.matcher(s);
        if (m.matches()) {
            System.out.println(s + " matches; first part is " + m.group(1) +
                               ", second part is " + m.group(2) + ".");
        } else {
            System.out.println(s + " does not match.");
        }
    }

    public static void main(String[] args) {
        checkString("123-4567");
        checkString("foo-bar");
        checkString("123-");
        checkString("-4567");
        checkString("123-4567-890");
    }
}

As the pattern is fixed in this instance, it can be compiled in advance and stored as a static member (initialised at class load time in the example). The regular expression is:

Use with AI(\d+)-(\d+)

The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the Match.group() method, as shown. The \d matches and single decimal digit, and the + means "match one or more of the previous expression). The - has no special meaning, so just matches that character in the input. Note that you need to double-escape the backslashes when writing this as a Java string. Some other examples:

Use with AI([A-Z]+)-([A-Z]+)          // Each part consists of only capital letters 
([^-]+)-([^-]+)            // Each part consists of characters other than -
([A-Z]{2})-(\d+)           // The first part is exactly two capital letters,
                           // the second consists of digits
🌐
IONOS
ionos.com › digital guide › websites › web development › string splitting in java
How to split strings in Java - IONOS
January 6, 2025 - In this example, a string variable x is ini­tial­ized. Then Java’s split() is used on the string. The parameter searches the string for spaces and splits it in the places where it finds them. The result is then saved in an array called “output”. The for loop is used to list the sub­strings.
🌐
How to do in Java
howtodoinjava.com › home › string › java string split(): limit, regex escaping and empty strings
Java String split() : Splitting by One or Multiple Delimiters
October 12, 2023 - A character class such as [,;] splits on any one of the listed characters, and adding + treats a run of delimiters as one. An alternation with | handles delimiters that are longer than one character, and \\s* around a delimiter removes the spaces next to it in the same step. String tags = "java, spring;docker kafka"; String[] anyOf = tags.split("[,;\\s]+"); // [java, spring, docker, kafka] String[] trimmed = "a , b ;c".split("\\s*[,;]\\s*"); // [a, b, c] String[] words = "one AND two OR three".split("\\s+(AND|OR)\\s+"); // [one, two, three]
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java string › split a string in java
Split a String in Java | Baeldung
January 8, 2024 - Let’s start with the core library – the String class itself offers a split() method – which is very convenient and sufficient for most scenarios. It simply splits the given String based on the delimiter, returning an array of Strings.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
July 21, 2026 - Splits this string around matches of the given regular expression.
🌐
Programiz
programiz.com › java-programming › library › string › split
Java String split() | Programiz
March 12, 2024 - The Java String split() method divides the string at the specified separator and returns an array of substrings. In this tutorial, you will learn about the Java split() method with the help of examples.
🌐
Sentry
sentry.io › sentry answers › java › how to split a string in java
Java String Split: Use String.split() With Regex | Sentry
September 23, 2026 - Split a string in Java using the String.split() method, which accepts a regex delimiter, requires escaping special characters, and handles edge case inputs
🌐
How to do in Java
howtodoinjava.com › home › string › split a string in java: split(), pattern, scanner and more
Split a String in Java: split(), Pattern, Scanner and More
3 weeks ago - To split a string in Java, we call String.split() with a delimiter regex, which returns a String[] of the parts between the matches.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › string_split.htm
Java - String split() Method
This method accepts a string representing a regular expression as a parameter, searches for the given pattern in the current string and, splits it at every match.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-split-method-example
Java String split() Method with examples
Java String split method is used for splitting a String into substrings based on the given delimiter or regular expression.
🌐
Codecademy
codecademy.com › docs › java › strings › .split()
Java | Strings | .split() | Codecademy
March 30, 2022 - Splits a string into an array of substrings based on a delimiter pattern.
🌐
Guru99
guru99.com › home › java tutorials › java string split() method with example
Java String split() Method with Example
July 30, 2026 - Split a String in Java using the split() method, which breaks text wherever a delimiter matches and returns the pieces as a String array.
🌐
Stack Abuse
stackabuse.com › how-to-split-a-string-in-java
How to Split a String in Java
September 20, 2023 - Splits the string variable at the | character. We use two backlashes here since we need to first escape the Java-meaning of the backlash, so the backslash can be applied to the | character.
🌐
CodeGym
codegym.cc › java blog › strings in java › java string split() method
Java String split method
December 5, 2024 - Let us analyze each of these separately as we break down the description given above. The method returns an array of strings. The declaration contains the following words: "In Java, the split method splits a string into substrings."
🌐
Udemy
blog.udemy.com › home › it & development › software development › understanding the java split string method
Understanding the Java Split String Method - Udemy Blog
April 14, 2026 - Using Java's `split()` method lets you divide a string into substrings based on a delimiter, returning a string array. This article covers basic syntax, working examples, and the two-parameter overload using a limit.