The following program, called RegExpExample.java, takes a simple regular expression and prints all lines from a file which contain a match.
NOTE: Complete code for this example is located in the examples directory created for your installation of Tools.h++ Professional. The "Examples" chapter in Part V, "Resources," describes the location of that directory, or you can check the online build guide for your installation media.
You might type the following command:
java RegExpExample "[0-9]" filename
to run this program:
import com.roguewave.tools.v2-0.RegExp; import java.io.*; public class RegExpExample { public static void main( String[] args ) { if (args.length < 2) { System.err.println("\nUsage: java RegExpExample <regexp>" + "<file>"); return; } // Build a regular expression out of the first argument string: RegExp re = new RegExp(args[0]); // Make sure the regular expression is valid before using it: if (re.status() != RegExp.OK) { System.err.println("Error: Bad regular expression"); return; } // Build an input stream for the file: FileReader fin; try { fin = new FileReader(args[1]); } catch( FileNotFoundException noFile ) { System.err.println("Error: File not found"); return; } // Decorate input stream with line numbers and data input // capability: LineNumberReader lin = new LineNumberReader(fin); // Read file line by line and search for regular expression: String line; try { while ( (line = lin.readLine()) != null ) { if ( (re.index(line))[0] >= 0) System.out.println(lin.getLineNumber() + ": " + line); } } catch(IOException io) { System.err.println("Error: IO exception on file read"); return; } } }
©Copyright 2000, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.