2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Case studies of regular expression in java

Usually we come across many situation which can be solve by using some simple regular expression. Some of them are as below:


Case 1: Find number of occurrence in a given string


Let's say the string is "abbbabbaba"

To find the number of occurrence using java code

import java.util.regex.*;
class RegularExpressionDemo 
{
   public static void main(String[] args) 
   {
      int count=0;
      Pattern p=Pattern.compile("ab");
      Matcher m=p.matcher("abbbabbaba");
      while(m.find())
      {
         count++;
         System.out.println(m.start()+"------"+m.end()+"------"+m.group());
      }
      System.out.println("The no of occurences :"+count);
   }
}

Output:

0------2------ab

4------6------ab

7------9------ab

The no of occurrences: 3


Case 2: A program to display all .txt file names present in folder

import java.util.regex.*;
import java.io.*;
class RegularExpressionDemo 
{
   public static void main(String[] args)throws IOException 
   {
      int count=0;
      Pattern p=Pattern.compile("[a-zA-Z0-9-$.]+[.]txt");
      File f=new File("<folder name>");
      String[] s=f.list();
      for(String s1:s)
      {
         Matcher m=p.matcher(s1);
         if(m.find()&&m.group().equals(s1))
         {
            count++;
            System.out.println(s1);
         }
      }
      System.out.println("Total File : " + count);
   }
}

Output:

input.txt

output.txt

outut.txt

Total File : 3


Case 3: A program to extract all valid mobile/email ids numbers from a file

import java.util.regex.*;
import java.io.*;
class RegularExpressionDemo 
{
   public static void main(String[] args)throws IOException 
   {
      // String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
      //   + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
      PrintWriter out=new PrintWriter("output.txt");
      BufferedReader br=new BufferedReader(new FileReader("input.txt"));
      Pattern p=Pattern.compile("[7-9][0-9]{9}");
      String line=br.readLine();
      while(line!=null)
      {
         Matcher m=p.matcher(line);
         while(m.find())
         {
            out.println(m.group());
         }
         line=br.readLine();
      }
      out.flush();
   }
}