Split
In this chapter you will learn:
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: