Categories
java split string

How do I split a string in Java?

1860

I want to split the string "004-034556" into two strings by the delimiter "-":

part1 = "004";
part2 = "034556";

That means the first string will contain the characters before '-', and the second string will contain the characters after '-'.

I also want to check if the string has '-' in it.

0

    3299

    +250

    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
    

    3

    • 31

      Why do you use hash symbols to delimit String’s methods?

      – Crowie

      Aug 1, 2013 at 8:56

    • 100

      @Crowie: javadoc-style.

      – BalusC

      Aug 1, 2013 at 12:04

    • 10

      Corner case: if it cannot find reugalr expression it returns one element array with whole string.

      – klimat

      May 23, 2016 at 12:36

    85

    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
    

    1

    • This is a great solution, however the first part should be m.group(1), the second part m.group(2), since m.group(0) actually returns the full matching pattern. I think i also remember group(0) used to be the first match instead of the full pattern, maybe this changed in a recent java version update.

      – ptstone

      Jul 13, 2017 at 4:28


    48

    Use:

    String[] result = yourString.split("-");
    if (result.length != 2) 
         throw new IllegalArgumentException("String not in correct format");
    

    This will split your string into two parts. The first element in the array will be the part containing the stuff before the -, and the second element in the array will contain the part of your string after the -.

    If the array length is not 2, then the string was not in the format: string-string.

    Check out the split() method in the String class.

    2

    • 6

      This will accept “-555” as input and returns [, 555]. The requirements aren’t defined that clear, if it would be valid to accept this. I recommend writing some unit-tests to define the desired behaviour.

      Aug 14, 2010 at 6:36

    • 1

      Probly safest to change (result.length != 2) to (result.length < 2)

      Feb 10, 2014 at 16:53