
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to split a regular expression in Java
Problem Description
How to split a regular expression?
Solution
Following example demonstrates how to split a regular expression by using Pattern.compile() method and patternname.split() method of regex.Pattern class.
import java.util.regex.Pattern; public class PatternSplitExample { public static void main(String args[]) { Pattern p = Pattern.compile(" "); String tmp = "this is the Java example"; String[] tokens = p.split(tmp); for (int i = 0; i < tokens.length; i++) { System.out.println(tokens[i]); } } }
Result
The above code sample will produce the following result.
this is the Java example
The following is an example to split a regular expression.
import java.util.regex.Pattern; public class Main { public static void main(String a[]) { String s1 = "Learn how to use regular expression in Java programming. Here are most commonly used example"; Pattern p1 = Pattern.compile("(use|Java|are|use)"); String[] parts = p1.split(s1); for(String p:parts) { System.out.println(p); } } }
The above code sample will produce the following result.
Learn how to regular expression in programming. Here most commonly d example
java_regular_exp.htm
Advertisements