The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.regex  [26 examples] > Lines  [6 examples]

e441. 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) {
    }

 Related Examples
e442. Implementing a FilterReader to Filter Lines Based on a Regular Expression
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

See also: Flags    Groups    Paragraphs    Searching and Replacing    Tokenizing   


© 2002 Addison-Wesley.