The length of the substring that was matched.
Here is a program that reads through the lines of a file one by one, looking in each line for a user-specified regular expression. (This is similar to the Unix command grep.)
import java.util.regex.*; import java.util.Scanner; import java.io.*; public class Grep { public static void main (String [] args) throws IOException { String line; int lines = 0; int matches = 0; // Check the command line, prompt user if needed if ( args.length != 2 ) { System.out.print("java Grep pattern fileName\n"); System.exit( 1 ); } System.out.print ("Find " + args[0]); System.out.println(" in " + args[1]); // Create a Scanner for the file File in = new File(args[1]); Scanner scan = new Scanner( in ); // Get a regular expression from the command line Pattern pat = Pattern.compile( args[0] ); // Match lines against the Regular Expression while ( scan.hasNextLine() ) { line = scan.nextLine(); lines++; // Check if the current line contains the pattern Matcher match = pat.matcher( line ); if (match.find()) { System.out.println ("" + lines + ": " + line); matches++; } } System.out.println( lines + " lines, " + matches + " matches" ); } }
How could the program be improved?