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

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.