Thursday, October 27, 2011

Java Regular Expressions Test Harness

Regular Expressions are best understood when we try them using java program with different inputs and analyzing output while reading the definitions.

Java Regex page provides a class that we can use to try out regular expressions with different inputs. But, the issue with this program is, it does not work in eclipse because of the access to Console from eclipse. If you are experiencing that issue, the below program can be used to try them out.

package org.apache.nutch.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTestHarness {
 public static void main(String[] args){
  try {
         BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
         System.out.println("Enter regual expression: ");
         String regex;
   regex = console.readLine();
         while (!regex.equalsIgnoreCase("exit")) {
 
             Pattern pattern = Pattern.compile(regex);
 
             System.out.println("Enter input string to search: ");
             Matcher matcher = pattern.matcher(console.readLine());
 
             boolean found = false;
             while (matcher.find()) {
                 System.out.println("I found the text '"+ matcher.group()+ "' starting at index " +matcher.start()+ " and ending at index "  +matcher.end());
                 found = true;
             }
             if(!found){
              System.out.println("No match found.%n");
             }
          System.out.println("Enter regual expression: ");
    regex = console.readLine();
         }
  } catch (IOException e) {
   e.printStackTrace();
  }
    }
}

No comments:

Post a Comment

Followers