Displays directory listing using regular expressions : Pattern « Development « Java Tutorial






import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.regex.Pattern;

public class MainClass {
  public static void main(String[] args) {
    File path = new File(".");
    String[] list;
    if (args.length == 0)
      list = path.list();
    else
      list = path.list(new DirFilter(args[0]));
    Arrays.sort(list);
    for (int i = 0; i < list.length; i++)
      System.out.println(list[i]);
  }
}

class DirFilter implements FilenameFilter {
  private Pattern pattern;

  public DirFilter(String regex) {
    pattern = Pattern.compile(regex);
  }
  public boolean accept(File dir, String name) {
    return pattern.matcher(new File(name).getName()).matches();
  }
}








6.34.Pattern
6.34.1.Try out regular expressions
6.34.2.Pattern.compile('(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$').matcher
6.34.3.Displays directory listing using regular expressions
6.34.4.Pattern.compile('!!').split
6.34.5.Pattern.compile('[frb][aiu][gx]).matcher('fix the rug with bags')
6.34.6.Pattern.compile(^java, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE)