How to split string literal using java regex

Some time we need to split a string literal based on some delimiters . Java regular expressions provides an easy way of doing it. Let see a sample java program used to split a string literal based on pre-defined delimiter.

MySplitter.java


import java.util.regex.*;

public class MySplitter {
       public static void main(String[] args) {
              String input = "www.naeemgik.blogspot.com";
              Pattern p = Pattern.compile("\\.");
              String pieces[] = p.split(input);
              for (int i = 0; i < pieces.length; i++) {
                     System.out.println(pieces[i]);
              }
       }
}


The output of above code would be:

   www
   naeemgik
   blogspot
   com

 

Newer Post Older Post

Leave a Reply

naeemgik. Powered by Blogger.