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
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
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-split-a-string-by-character
Java - Split a String by Character - GeeksforGeeks
July 23, 2025 - In Java, we can use the split() method from the String class to split a string by character, which simplifies this process by taking a regular expression (regex) as its argument. It returns an array of strings, allowing us to easily manipulate ...
Discussions

java - Split string into array of character strings - Stack Overflow
Show activity on this post. I need to split a String into an array of single character Strings. Eg, splitting "cat" would give the array "c", "a", "t" ... As a quick reference, "".join(["c","a","t"]) to get "cat" back. ... Java 8: .split("") will do it. More on stackoverflow.com
🌐 stackoverflow.com
Split a string with multiple delimiters

Erm, you can just put all of the delimiters you want in the quotes for the string passed to .split()

[PS] C:\Users\> $string = "part1.part2;part3"
[PS] C:\Users\> $string.split(".;")
part1
part2
part3
More on reddit.com
🌐 r/PowerShell
7
19
October 14, 2014
Split String every nth char / or the first occurrence of a period
No, because those two statements contradict; you can't break up the string by every 15th character, and also have each end with a period. hello world. my name is bob. how are you doing today abcd. efghijklmnop You could achieve something like this using String.replaceAll and a regular expression, but it doesn't break it up by every 15th character; some of these lines are more than 15 characters. hello world. my name is bob. how are you doing today abcd. efghijklmnop. You could achieve something like this using the WordUtils class from commons-lang. It word wraps the string by every 15th character, but several lines don't always end in a "." Hopefully this starts you toward the right path. More on reddit.com
🌐 r/java
8
0
August 28, 2013
[JAVA] splitting a string at a "{}"
It is expecting regular expression : public String[] split(String regex) Splits this string around matches of the given regular expression. In regular expression, {} is usually used to set the minimum and maximum occurrences of a group/class/character. From the docs , under sections ending with "quantifiers": X{n} - X, exactly n times X{n,} - X, at least n times X{n,m} - X, at least n but not more than m times What you basically do is you put {} into character classes (seperated by a comma). Your expression can be rewritten to "\\},\\{". More on reddit.com
🌐 r/ProgrammerTIL
3
3
November 22, 2017
🌐
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 - This means that if you want to split a string on a character that has special meaning in regular expressions, you need to escape it. For example, to split a string on a period (.), use str.split("\\."). public class Main { public static void main(String[] arg) { String str = "how.to.split.a.string.in.java"; String[] arrOfStr = str.split("\\."); for (String a : arrOfStr) { System.out.println(a); } } } This example also has the same output as the previous examples.
🌐
Baeldung
baeldung.com › home › java › java string › java string.split()
Java.String.split() | Baeldung
July 15, 2026 - For example, if we want to split on a dot (.), we need to escape it like this: \\. because the dot (.) is a special character in regular expressions: @Test void whenSplitWithDotDelimiter_thenGetExpectedArray() { String s = "www.example.com"; String[] expected = new String[] { "www", "example", "com" }; String[] result = s.split("\\."); assertArrayEquals(expected, result); } Once data is in a Java String, it’s already decoded into a sequence of Unicode characters.
🌐
Stack Abuse
stackabuse.com › how-to-split-a-string-in-java
How to Split a String in Java
September 20, 2023 - One way we can use this is to use a backslash \. For example: ... 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.
🌐
Briebug
blog.briebug.com › home › articles › using the java string.split() method
Using the Java String.split() Method | Briebug
October 13, 2022 - This example uses both a single character delimiter and a regular expression to get a feel for the different ways it can be used. Below is our first example using the first variation and it’s output. Be sure to read the code carefully and try it out on your own. When it comes to coding, the best way to get better is practice. Alright, time to dive into some code! public class StringSplitExample { public static void main(String[] args) { String ourString = "This,is,a,comma,separated,string"; String[] ourStringSplitArray = ourString.split(","); for (String split : ourStringSplitArray) { System.out.println(split); } System.out.println("***** String.split() with Regex.
🌐
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.
Find elsewhere
🌐
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; ... System.out.println(output); } } ... We can use \\s+ (which means one or more whitespace characters in regex) to split a string by spaces....
🌐
Medium
medium.com › @AlexanderObregon › javas-string-split-method-explained-77bdaddaae79
Java’s String split() Method Explained
June 25, 2024 - Even though the string is empty, the split() method returns an array with one element (the empty string itself). If the delimiter is empty (""), the split() method will return an array of single-character 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 ...
🌐
Coderanch
coderanch.com › t › 560479 › java › Split-string-word-character
Split string on a word not just a character (Java in General forum at Coderanch)
December 1, 2011 - You could put whitespace in your regex in order to split on the words. \s means "any whitespace (tab, newline, space, new paragraph etc) character. s = s.split("\sthe\s"); ... Rob Spoor wrote:To also allow "the" at the start and end of the String, make that And if you want to allow for more than one whitespace character, you might need: split("(\\s+|^)the(\\s+|$)") and you may need to worry about whether you use greedy or reluctant qualifiers (to be honest, I don't know if it makes any difference).
🌐
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.
🌐
Real's HowTo
rgagnon.com › javadetails › java-0438.html
Split a string using String.split() - Real's Java How-to
public class StringSplit { public static void main(String args[]) throws Exception{ String testString = "Real|How|To"; // bad System.out.println (java.util.Arrays.toString(testString.split("|"))); // output : [, R, e, a, l, |, H, o, w, |, T, o] // good System.out.println (java.util.Arrays.toString(testString.split("\\|"))); // output : [Real, How, To] } } The special character needs to be escaped with a "\" but since "\" is also a special character in Java, you need to escape it again with another "\" !
🌐
IONOS
ionos.com › digital guide › websites › web development › string splitting in java
How to split strings in Java - IONOS
January 6, 2025 - The method split() can be used to split strings in Java. It contains a parameter for the separator and an optional parameter for the number of sub­strings. There are also some par­tic­u­lar­i­ties to note when using the method.
🌐
Codefinity
codefinity.com › courses › v2 › 0bfa1111-8677-478f-bcd3-315dff1d7d40 › 421ab035-77e8-4fef-abb9-488c91c2d1f9 › 433c4bac-9f33-4b48-9be0-cdc81423c941
Learn Method split() | String Advanced
The split(String delimiter) method splits a string into an array of substrings based on the specified delimiter (a character or sequence of characters).
🌐
Medium
medium.com › sina-ahmadi › java-regex-6e4d073aab85
Java RegEx. special characters issue in Java split… | by Sina | My journey as a software developer | Medium
June 20, 2018 - Replace all special characters using Java’s “replaceAll” method in the input string, with escaped special characters ... escapedString = nonEscapedString.replaceAll("\\*", "\\\\*"); splittedString = escapedString.split("\\*")
🌐
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 - For instance, using split(“\\s+”) allows you to split a string based on one or more whitespace characters simultaneously. For more complex patterns, mastering Java Regular Expressions is highly recommended.
🌐
YouTube
youtube.com › watch
How to split a Java String - 052 - YouTube
In this tutorial we're going to look at how to split a string in Java. We can split the string by character or split the string by words. We'll look at both!...
Published: December 12, 2016
🌐
xperti
xperti.io › home › split() string method in java with example
Split() String Method in Java: A guide to Split Strings in Java
August 3, 2022 - Java string split() method allows the user to split a string into one or more substrings based on a specific Java string delimiter or a regular expression. The delimiter can be any character but the most commonly used characters are comma(,) space or a dot(.)....