Introducing patternchecker

January 24, 2010

Often I need a small utility script/program to check the matched results of regex pattern against known text. So I dont have to execute my lengthy main script/program multiple times to get the correct pattern.

I’ve used the following patternchecker script (PERL) & program (JAVA) while coming up with patterns and for demonstration in my previous posts.

Usage:
# java patterncheck
Enter pattern : (x*)(x)(x+)
Enter string:foxxxxx
Matched : fo<<< xxxxx >>>
group 1 = xxx
group 2 = x
group 3 = x

Perl and Java uses the same regex engine and thus would behave similarly while matching patterns, I’ve listed here the sourcecode in perl and java out of my curiosity although you just need any one of them,

i) perl

#!/usr/bin/perl
print "Enter pattern :";
### Read the regex pattern
chomp($pattern=<STDIN>);

### count the number of paranthesis
$cnt++ while( $pattern =~ /\(/g );
print "Enter string :";
chomp($input=<STDIN>);

### read the string to be tested against
if ( $input =~ /$pattern/ ){

      ### print prematch, match, postmatch
      print "Matched: $`<<< $& >>> $'\n";

      ### print $1, $2, etc
      foreach $i (1..${cnt}) { print "\$",$i," = ",${$i},"\n";}
} else {
      print "No Match\n";
}
<div>

ii) java

import java.lang.*;
import java.io.*;
import java.util.regex.*;

public class patterncheck{
	public static void main(String args[]){
		String pattern, str;
		int groups;

		//Read pattern and string from the console
		Console c = System.console();
		pattern=c.readLine("%s","Enter pattern :");
		str=c.readLine("%s","Enter string:");

		//compile and associate the pattern with the text
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(str);

		//if there is a match
		if (m.find()){
			// print prematch, match & postmatch
			System.out.println("Matched : "+str.substring(0,m.start())+"<<< "+ m.group() +" >>>"+str.substring(m.end()));

			// print what captured in paranthesis
			if (m.groupCount() != 0) {
				groups=m.groupCount();
				for (int i=1;i<=groups;i++){
					System.out.println("group "+i+" = "+m.group(i));
				}
			}
		}
		else {
			System.out.println("No Match");
		}
	}
}