Home »
Java »
Java Programs
Java program to demonstrate the split() method of Pattern class
Java example to demonstrate the split() method of Pattern class.
Submitted by Nidhi, on June 12, 2022
Problem statement
In this program, we will create a string and a regular expression pattern. Then we will use the split() method to split the given input sequence around matches of this pattern.
Java program to demonstrate the split() method of Pattern class
The source code to demonstrate the split() method of the Pattern class is given below. The given program is compiled and executed successfully.
// Java program to demonstrate the split() method
// of Pattern class
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String str = "bcd abc xyz abc pqr lmn";
String regex = "ABC";
int iLoop = 0;
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
String[] result = pattern.split(str);
for (iLoop = 0; iLoop < result.length; iLoop++)
System.out.println(result[iLoop]);
}
}
Output
bcd
xyz
pqr lmn
Explanation
In the above program, we imported the "java.util.regex.*" package to use the Pattern and Matcher classes. Here, we created a public class Main.
The Main class contains a main() method. The main() method is the entry point for the program. And, created a string and pattern. Then we used the compile() to search for a pattern in the string. After that, we used the split() method to split the given input sequence around matches of this pattern and returned the array of strings. After that, we printed the result.
Java Regular Expressions Programs »