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
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › split() string method in java and delimiters
Understanding the Split() String Method in Java
December 22, 2024 - The array returned by the method contains each substring terminated by another substring that matches the given expression or terminated by end of string. The order of substrings returned will be the same as they occur in the given string. If there is no match found for the delimiter provided, the resulting array of string will contain the single string provided. Strings in Java can be parsed using the split method. Following are the points to be considered while using the split method: ... In Java, delimiters are characters that separate the strings into tokens.
Top answer
1 of 16
3415

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
People also ask

Between String.Split and StringTokenizer, which is better?
Generally, StringTokenizer is faster in terms of performance, but String.split is more reliable. The split method of String and the java.util.regex package incur the significant overhead of using regexes, hence making it slow. StringTokenizer does not use java.util.regex and therefore gives better performance. On the other hand, String split returns an array of results and is more convenient to use than StringTokenizer.
🌐
interviewkickstart.com
interviewkickstart.com › home › blogs › learn › split() string method in java and delimiters
Understanding the Split() String Method in Java
What is the best application of the string split method?
For validating official email IDs, we can easily split the string using the @ symbol, and then we can validate both the email as well as the domain name in the resultant array. It can also be used to parse data from a file line by line.
🌐
interviewkickstart.com
interviewkickstart.com › home › blogs › learn › split() string method in java and delimiters
Understanding the Split() String Method in Java
🌐
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. Instead of this, we can use a regex character set This refers to putting the special characters to be escaped inside square brackets. This way, the special characters are treated as normal characters. For example, we could use a | as a delimiter by ...
🌐
Sentry
sentry.io › sentry answers › java › how to split a string in java
How to split a string in Java | Sentry
May 15, 2023 - public class Main { public static ... regular expression. This means it is easy to do things like split on one or more : characters by using :+....
🌐
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.
🌐
BeginnersBook -
beginnersbook.com › home › java › java string split() method with examples
Java String split() Method with examples
December 1, 2024 - Input: "Just.a.Simple.String"; Output: ["Just", "a", "Simple", "String"] ... The ?! part in this regex is negative assertion, which it works like a not operator in the context of regular expression. The ^ is to match the beginning of the string. Together it matches any character that is not ...
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java string › java string.split()
Java.String.split() | Baeldung
March 13, 2025 - In this article, we explored the String.split() method, which allows us to divide strings into smaller substrings based on specified delimiters. We learned how to use this method with regular expressions, handle different character encodings, ...
🌐
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 - Regexes are good, but they're not all-powerful, and trying to incorporate every possible rule into one is likely to make for a very long and complicated pattern (and will probably lead to more mistakes). What about this: 1. Use String.split("\\s+") to split the string into whitespace-delimited ...
🌐
Scaler
scaler.com › home › topics › split() string method in java with examples
split() String Method in Java with Examples - Scaler Topics
April 11, 2024 - ... The split() method raises an ... provided is invalid. ... Note: If we need to use a special character such as \, |, ^, *, + etc., we can use an escape sequence to escape these characters....
🌐
Briebug Blog
blog.briebug.com › blog › java-split-string
Using the Java String.split() Method
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.
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › split
Java String split() - Split String | Vultr Docs
December 17, 2024 - The pattern [ ,;\\s]+ is used to split the string whenever a comma, semicolon, or any whitespace character is encountered. Note that empty strings may appear in the result of a split due to leading, trailing, or consecutive delimiters.
🌐
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.
🌐
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.
🌐
Coderanch
coderanch.com › t › 771194 › java › string-split-method-work
Why does my string.split(.) method not work? (Beginning Java forum at Coderanch)
March 19, 2023 - Stephan van Hulst wrote:In longer ... only one character. It's become a bit of a habit for me, so even in a simple case like this I'd probably write string.split("[.]"). There's not obvious advantage to it though, it's just personal preference. Yep, This is Backslash Hell. Other languages avoided this by using a special syntax for regex strings. For example, instead of "\\." they'd say /\./ But Java didn't wise ...
🌐
Quora
quora.com › How-do-I-split-a-String-at-using-split-method-in-Java
How to split a String at '.' using .split() method in Java - Quora
But if you want to split on a *special character you need to use the backslash \ or a character class [“ ”] to escape these characters. So in your case you would have .split(“\\.”) or .split(“[.]”) - Example below: [code]pub...
🌐
GeeksforGeeks
geeksforgeeks.org › java › split-string-java-examples
Java String split() Method - GeeksforGeeks
December 20, 2025 - split() method in Java is used to divide a string into an array of substrings based on a specified delimiter or regular expression.
🌐
UiPath Community
forum.uipath.com › help › activities
How to split string based on special character - Activities - UiPath Community Forum
Hi guys i’m facing a issue of splitting the name based on special character. Ex: 1) Ram kumar & rajesh & raja reddy 2)10-01-2021 & 15-01-2021 o/p : 1) Ram kumar rajesh raja reddy 10-01-2021 15-01-2021 I want th…
Published   January 20, 2021
🌐
Tutorialspoint
tutorialspoint.com › home › java/lang › java string split
Java String Split
September 1, 2008 - The Java String split() method is used to divide/split a string into an array of substrings. 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 ...
🌐
Oracle
forums.oracle.com › ords › apexds › post › java-split-without-delimiter-split-every-4-characters-1872
Java Split() without delimiter. Split every 4 characters
July 11, 2007 - Hello! I am trying to use the split funtion to split a string that contains no delimiter. The string is: 00f1002100410076000700a700c700f1 and I need the output to be: 00f1 0021 0041 0076 0007 00a...
🌐
Quora
quora.com › How-can-I-break-a-string-into-individual-chars-in-java
How to break a string into individual chars in java - Quora
Answer (1 of 5): Simple programme that i used to break a string into individual characters :- [code]import java.util.*; class arraytochar{ public static void main(String args[]) { Scanner s=new Scanner(System.in); String a=s.next(); int t=a.length(); char aa[]=new char[t]; int i=0; ...