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 usereset()
API method of Matcher to reset the matcher with the new line and print the line that matches the pattern usingfind()
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.