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