Chapter16a.java
Select all
/* Chater16a.java CIS 260 David Klick 2016-02-15 This program demonstrates regular expressions used with the String.matches method. */ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.FileSystems; import java.nio.charset.Charset; import java.util.List; import java.util.ArrayList; import java.io.IOException; public class Chapter16a { private static final boolean DISPLAY = true; private static class SearchPair { public String pattern, description; public SearchPair(String p, String d) { pattern = p; description = d; } } public static void main(String[] args) { int match = 0; List
lines; SearchPair[] search = { new SearchPair("a.*", "Starts with \"a\""), new SearchPair("aa.*", "Starts with \"aa\""), new SearchPair(".*a.*", "Contains an \"a\""), new SearchPair(".*aa.*", "Contains an \"aa\""), new SearchPair("a.*a", "Starts and ends with an \"a\""), new SearchPair(".*a.*a.*a.*", "Contains three \"a\"s"), new SearchPair(".*([ai]).*\\1.*\\1.*", "Contains three \"a\"s or \"i\"s"), new SearchPair(".*(bob|carol|ted|alice).*", "Contains bob or carol or ted or alice") }; try { Path path = FileSystems.getDefault().getPath("", "dict.txt"); lines = Files.readAllLines(path, Charset.defaultCharset()); for (SearchPair p : search) { match = 0; String pat = p.pattern; System.out.println(p.description); for (String line : lines) { if (line.matches(pat)) { if (DISPLAY) System.out.println(line); match++; } } if (match == 0) System.out.println("No matches found\n"); else System.out.println(match + " matches found\n"); } } catch (IOException e) { System.out.println("Error opening or reading input file"); } } }