![]() |
The Java Developers Almanac 1.4 |
|
e441. Using a Regular Expression to Filter Lines from a ReaderA common use of regular expressions is to find all lines that match a pattern, similar to thegrep Unix command. This example reads lines
using a BufferedReader and tests each line for a match.
try {
// Create the reader
String filename = "infile.txt";
String patternStr = "pattern";
BufferedReader rd = new BufferedReader(new FileReader(filename));
// Create the pattern
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher("");
// Retrieve all lines that match pattern
String line = null;
while ((line = rd.readLine()) != null) {
matcher.reset(line);
if (matcher.find()) {
// line matches the pattern
}
}
} catch (IOException e) {
}
e443. Matching Line Boundaries in a Regular Expression e444. Matching Across Line Boundaries in a Regular Expression e445. Reading Lines from a String Using a Regular Expression e446. Removing Line Termination Characters from a String
© 2002 Addison-Wesley. |