/** * RegexDates.java * * Class to demonstrate how to use regular expressions from the * Java 1.4 regex facility. * * This is just to get you started; changes will be needed to * do the full job. * * @author Marti Hearst 11/12/02 * @version 1.0 */ import java.io.*; import java.util.regex.*; public class RegexDates { private Pattern compiledRegex; private int monthIndex; private int dateIndex; private int yearIndex; /* The constructor code creates a regular expression compiler. It defines the regex patterns and where to find the various pieces, for use by matcher.group(). This only covers a subset of all the date formats to be processed. More patterns will need to be added. */ RegexDates() { String month = "(jan|feb|mar|april|may|jun|jul|aug|sep|oct|nov|dec)"; String year = "(?:19|20|')([0-9]{2})"; String date = "([1-3]?[0-9]),?"; monthIndex = 1; dateIndex = 2; yearIndex = 3; String textPattern = month + " " + date + " " + year; compiledRegex = Pattern.compile(textPattern, Pattern.CASE_INSENSITIVE); } public Matcher getMatcher(String str) { return compiledRegex.matcher(str); } public String getMonth(Matcher m) { return (m.group(monthIndex)); } public String getDate(Matcher m) { return (m.group(dateIndex)); } public String getYear(Matcher m) { return (m.group(yearIndex)); } /* showMatches() This shows how to use the regex routines both to match a date and to extract out and use the components of that date. */ public void showMatches(String str) { Matcher matcher = getMatcher(str); try { if (matcher.find()) { System.out.println("\nFound a valid date: " + matcher.group(0)); System.out.println("\nMonth:\t " + getMonth(matcher) + " Date:\t " + getDate(matcher) + " Year:\t " + getYear(matcher)); } else { System.out.println("\nNo valid date: " + str); } } catch(IllegalStateException e){ System.out.println("\nNo Match or Malformed Regular Expression:\n" + e.getMessage()); } } // This just demonstrates how to get started. // Your code will need to process input from a file. See // http://javaalmanac.com/egs/java.util.regex/LineFilter2.html public static void main (String args[]) { String date1 = "jan 22, 2001"; String date2 = "It is the case that May 1, '93 was an auspicious date."; String date3 = "feb 27, 201"; RegexDates r = new RegexDates(); r.showMatches(date1); r.showMatches(date2); r.showMatches(date3); } }