
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Demonstrate the Usage of the Pattern Split Method in Java
The specified input sequence can be split around a particular match for a pattern using the java.util.regex.Pattern.split() method. This method has a single parameter i.e. the input sequence to split and it returns the string array obtained by splitting the input sequence around a particular match for a pattern.
A program that demonstrates the method Pattern.split() in Java regular expressions is given as follows:
Example
import java.util.regex.Pattern; public class Demo { public static void main(String[] args) { String regex = "_"; String input = "Oranges_are_orange"; System.out.println("Regex: " + regex); System.out.println("Input: " + input); Pattern p = Pattern.compile(regex); String[] str = p.split(input); System.out.println("\nThe split input is:"); for (String s : str) { System.out.println(s); } } }
Output
Regex: _ Input: Oranges_are_orange The split input is: Oranges are orange
Now let us understand the above program.
The regex and the input values are printed. Then the input sequence is split around the regex value using the Pattern.split() method. The split input is printed. A code snippet which demonstrates this is as follows:
String regex = "_"; String input = "Oranges_are_orange"; System.out.println("Regex: " + regex); System.out.println("Input: " + input); Pattern p = Pattern.compile(regex); String[] str = p.split(input); System.out.println("\nThe split input is:"); for(String s : str) { System.out.println(s); }
Advertisements