Simple implementation of the ubiquitous grep command. - Java Regular Expressions

Java examples for Regular Expressions:Match

Description

Simple implementation of the ubiquitous grep command.

Demo Code

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 {
    Pattern pattern = Pattern.compile("test");
    Matcher matcher = pattern.matcher("test");
    String file = "text.txt";
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;/*from   w ww .j  a v  a2 s. c om*/
    while ((line = br.readLine()) != null) {
      matcher.reset(line);
      if (matcher.find()) {
        System.out.println(file + ": " + line);
      }
    }
    br.close();
  }
}

Related Tutorials