Printing Lines Containing a Pattern


String pattern = "^a"; Pattern regPat = Pattern.compile(pattern); Matcher matcher = regPat.matcher(""); BufferedReader reader =    new BufferedReader(new FileReader("file.txt")); String line; while ((line = reader.readLine()) != null) {     matcher.reset(line);     if (matcher.find()) {          System.out.println(line);     } }



This phrase demonstrates how we might search through a file to find all the lines that contain a given pattern. Here we use the BufferedReader class to read lines from a text file. We attempt to match each line against our pattern using the find() method of the Matcher class. The find() method will return true if the pattern is found within the line passed as its parameter. We print all the lines that match the given pattern. Note that this piece of code can throw FileNotFoundException and IOException, and these would need to be handled in your real code. In this phrase, the regular expression would match any lines contained in our input file that start with the lowercase letter a.

The regular expression pattern we use is broken down as follows:

^  Special regular expression character    matching the beginning of a string. a  matches the character letter a.





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net