Using a Regular Expression to Filter Lines from a Reader

A common use of regular expressions is to find all lines that match a pattern, similar to the grep 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) { }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.