How to Split String in Java using Regular Expression (original) (raw)

String class provides split() method to split String in Java, based upon any delimiter, e.g. comma, colon, space or any arbitrary method. split() method splits the string based on delimiter provided, and return a String array, which contains individual Strings. Actually, split() method takes a regular expression, which in simplest case can be a single word. split() is also overloaded method in java.lang.String class and its overloaded version take a limit parameter which is used to control how many times the pattern will be applied during the splitting process. if this limit is positive n, then the pattern will be applied at most n-1 times, if it's negative or zero then split operation is applied any number of times.

For example, if we split String "First,Second,Third" on comma and provide limit as 2 then pattern will run one time, and split() will return String array with 2 Strings, "First" and "Second,Third".

Since this method accepts a Java regular expression, it throws PatternSyntaxException, if the syntax of the regular expression is invalid.

String Split Example in Java

String Split Example with regular expression in JavaLet's see a couple of String Split example in Java. In the first example, we will split a colon separated String on colon as a delimiter, and in the second example, we will split comma separated String.

In the third example, we will split String using the regular expression, which actually splits a String on space as delimiter. \\s is a regular expression to find spaces. \s is actually used to match any white space character including newline, tab, form feed e.g. \t, \n, \r, and \f. \\ is to escape backward slash which is an escape character in Java.

If you are familiar with Java Regular Expression, then split(regex) method is similar to Pattern.compile(regex).split().

package test;

/**

} Output: Original Colon Separated String : Java:J2EE:JavaFX:JavaME String splitted using Split() method of java.lang.String in Java Java J2EE JavaFX JavaME Original comma separated String : Android,Windows 8,iOS,Symbian Splitting String using split() method in Java Android Windows 8 iOS Symbian Space separated String before split : String Split Example in Java Space separated String after split String Split Example in Java

That's it on How to split String in Java using delimiter and regular expression. The split(regex) method is very powerful, and all its power comes from the regular expression. Though it's not required to know regular expressions to split String in Java, but if you know regex, it is only going to help you.

Related Java String tutorials from Java67 Blog