regex

Filter lines from reader example

In this example we shall show you how to filter lines from a Reader. To filter lines from a Reader one should perform the following steps:

  • Create a new BufferedReader that uses a FileReader with a given name of a file to read from.
  • Compile a given String regular expression to a Pattern, using compile(string regex) API method of Pattern.
  • Use matcher(CharSequence input) API method of Pattern to get a matcher that will match the given buffered reader against this pattern.
  • Read the lines of the text using readLine() API method of BufferedReader and for each line use reset() API method of Matcher to reset the matcher with the new line and print the line that matches the pattern using find() API method of Matcher,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] argv) throws Exception {
    String filename = "infile.txt";
    String patternStr = "pattern";
    BufferedReader rd = new BufferedReader(new FileReader(filename));

    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher("\D");

    String line = null;
    while ((line = rd.readLine()) != null) {

matcher.reset(line);

if (matcher.find()) {

  System.out.println(line);

}
    }
  }
}

 
This was an example of how to filter lines from a Reader in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button