Java String split(String regex) method example

HQ » Java Tutorial » java.lang » String » split(String regex) method example
Java String split(String regex) method example 2018-02-19T13:02:27+00:00

java.lang.String split(String regex)

Description :

This java tutorial shows how to use the split(String regex) method of String class of java.lang package. This method returns a character array which corresponds to the result of splitting the String object given a java regular expression as a method parameter.

Method Syntax :

public String[] split(String regex)

Parameter Input :

DataType Parameter Description
String regex This is the java regular expression that we will be using in splitting the String object

Method Returns :

This String split() method with argument regex returns an array of String. The regex parameter will be used in evaluating how we can split the String object.

Compatibility Version :

Requires Java 1.5 and up

Exception :

PatternSyntaxException

This exception will be thrown if and only if the regex pattern specified on the method parameter is invalid.

Discussion :

I really can’t remember how many times do i have to use the split method. This is a very convenient method in breaking down a String object into smaller object based on the pattern provided as regex method parameter.

Supposed we have to break down a pipe(|) delimited String like for example we have a string object “Andrew|M|USA”. As you can see on our string object we have 3 token that we could extract. Using the String split method, we would be able to convert this object into String array.

Java Code Example :

This example source code demonstrates the use of [method name] method of String class. Basically it just converts a String object in the format Name:AGE:Country into a String array.

Sample Output :

Running the split() method example source code of String class will give you the following output

java string split method example

java string split method example

Exception Scenario :

Similar Method :

  • java.lang.String split(String regex, int limit)

Suggested Reading List :

 

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close