O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required