Split

In this chapter you will learn:

  1. How to split a string with Java regular expression

Using split()

You can reduce an input sequence into its individual tokens by using the split() method defined by Pattern. One form of the split() method is shown here:

String[] split(CharSequence str)

It processes the input sequence passed in str, reducing it into tokens based on the delimiters specified by the pattern.

For example, the following program finds tokens that are separated by spaces, commas, periods, and exclamation points:

import java.util.regex.Pattern;
/*  java2  s  . c  o  m*/
public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("[ ,.!]");
    String strs[] = pat.split("This is, a test!");
    for (int i = 0; i < strs.length; i++)
      System.out.println("Next token: " + strs[i]);
  }
}

Output:

From the result we can see that each word is separated by the delimiters we defined in the pattern.

Next chapter...

What you will learn in the next chapter:

  1. Multithreaded Programming
  2. A counting thread
Home » Java Tutorial » Regular Expressions
Regular Expression Processing
Normal characters
Character class
Wildcard Character
Quantifier
Wildcards and Quantifiers
Character class and quantifiers
Find sub string
Multiple subsequences
Replace all
Split