November 2006
Intermediate to advanced
224 pages
3h 29m
English
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 ...