String Split in Java using Pattern.split() Example Code using Regular Expression (util.regex)

The following program splits the given string using the split method of Pattern Calss of the package java.util.regex available with JDK 1.4 onwards. An instance of the Pattern class represents a regular expression which is specified in string . Pattern Class has various methods . Some of the methods are as follows.

1. compile(String regex) -> Compiles the given regular expression into a pattern.
2. split(CharSequence input) -> Splits the given string using the pattern.
3. matches(String regex, CharSequence input) -> Compiles the given regular expression (regex) and Matches the given input string against it.

The following Program splits the given input string by the delimiter # , white space and commas

   

import java.util.regex.*;
import java.util.Scanner;
public class SplitByRegex {
public static void main(String[] args) throws Exception {

Pattern pattern = Pattern.compile("[#,\\s]+"); // created pattern using # comma whitespace

Scanner sc=new Scanner(System.in).useDelimiter("\n"); //Accepts Line of String
System.out.println("Enter Line to Split "); //
String inputStr=sc.next();
System.out.println("Enterd Line : " + inputStr + "\n");
String[] resultStr = pattern.split(inputStr);
System.out.println("\nResult Strings after Split\n");
for (int i=0; i<resultStr.length; i++)
System.out.println((i+1) +"." + resultStr[i]);
}
}

Running the Program :

D:\as2\JF1>java SplitByRegex
Enter Line to Split
Mumbai # Calcutta # Chennai # Delhi , US, Washinton , Canada Singapore Malasia
India
Enterd Line : Mumbai # Calcutta # Chennai # Delhi , US, Washinton , Canada Sing
apore Malasia India


Result Strings after Split

1.Mumbai
2.Calcutta
3.Chennai
4.Delhi
5.US
6.Washinton
7.Canada
8.Singapore
9.Malasia
10.India

1 comments:

javin paul said...

Nice article man, you have covered the topic quite well. I have also blogged about How to split string in Java, let me know how do you find it .

Thanks
Javin

Post a Comment

 
Copyright 2011 Java Online