Use the appropriately named method String#split().

String 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(".")).

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

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

if (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.

String 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.

String 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.

String 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.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
July 21, 2026 - the array of strings computed by splitting this string around matches of the given regular expression ... Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. ... String message = String.join("-", "Java", "is", "cool"); ...
🌐
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.
Top answer
1 of 16
3416

Use the appropriately named method String#split().

String 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(".")).

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

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

if (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.

String 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.

String 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.

String 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:

import 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:

(\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:

([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
🌐
Baeldung
baeldung.com › home › java › java string › java string.split()
Java.String.split() | Baeldung
July 15, 2026 - This method returns an array of strings. Each element in the array is a substring from the original string. The regex is the regular expression that defines the delimiter. We can also pass a limit on the number of splits to the split() method.
🌐
Programiz
programiz.com › java-programming › library › string › split
Java String split()
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.
🌐
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."
🌐
Medium
medium.com › @AlexanderObregon › javas-string-split-method-explained-77bdaddaae79
Java’s String split() Method Explained
June 25, 2024 - The split() method allows you to divide a string into an array of substrings based on a specified delimiter, which can be useful in various scenarios such as parsing data, manipulating text, and more.
Find elsewhere
🌐
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.
🌐
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() : splitting by one or multiple delimiters
Java String split() : Splitting by One or Multiple Delimiters
October 12, 2023 - For using the multiple delimiters, the regular expression should define a character class that includes all the delimiters we want to split by. The regular expression must be a valid pattern and we must remember to escape special characters if necessary. String str = "how-to-do.in.java"; String[] strArray1 = str.split("-"); //[how, to, do.in.java] - 3 tokens String[] strArray2 = str.split("-|\\."); //[how, to, do, in, java] - 5 tokens
🌐
Mkyong
mkyong.com › home › java › how to split a string in java
How to split a string in Java - Mkyong.com
February 9, 2022 - package com.mkyong.string.split; import java.util.regex.Pattern; public class StringSplitSpecialPipe { public static void main(String[] args) { String csv = "a|b|c|d"; // Three ways to escape regex special character // String[] output = csv.split("\\|"); // String[] output = csv.split("[|]"); String[] output = csv.split(Pattern.quote("|")); for (String s : output) { System.out.println(s); } } }
🌐
Briebug
blog.briebug.com › home › articles › using the java string.split() method
Using the Java String.split() Method | Briebug
October 13, 2022 - The Java String.split() method has two variations, commonly known as method overloading, which are both used to split a String into an array of Strings, using a passed delimiter or regular expression.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › string_split.htm
Java - String split() Method
package com.tutorialspoint; public class StringDemo { public static void main(String[] args) { String str = "a d, m, i.n"; String delimiters = "\\s+|,\\s*|\\.\\s*"; // analyzing the string String[] tokensVal = str.split(delimiters); // prints the number of tokens System.out.println("Count of tokens = " + tokensVal.length); for(String token : tokensVal) { System.out.print(token); } } } If you compile and run the program above, the output will be displayed as follows − ... In this example, we are creating a Java String object with the value "WelcomeLaughtoLaughtutorialsPoint" and we are trying to split this string each time we encounter the substring "laugh".
🌐
Stack Abuse
stackabuse.com › how-to-split-a-string-in-java
How to Split a String in Java
September 20, 2023 - The split() method of the Java String class is a very useful and often used tool.
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › java string split() method: syntax, delimiters, and examples
Understanding Java String Split() Method | Interview Kickstart
April 1, 2026 - While StringTokenizer is faster ... split method is a built-in function of the java.lang.The String class is used to decompose a string into an array of substrings....
🌐
Guru99
guru99.com › home › java tutorials › split() string method in java: how to split string with example
Split() String Method in Java: How to Split String with Example
December 26, 2023 - StrSplit() method allows you to break a string based on specific Java string delimiter. Mostly the Java string split attribute will be a space or a comma(,) with which you want to break or split the string
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › split
Java String split() - Split String | Vultr Docs
December 17, 2024 - The Java split() method is a part of the String class in Java, used extensively for dividing a string into multiple parts based on a specified delimiter.
🌐
Baeldung
baeldung.com › home › java › java string › split a string in java
Split a String in Java | Baeldung
January 8, 2024 - Let us look at some examples. We’ll start with splitting by a comma: String[] splitted = "peter,james,thomas".split(",");