270 likes | 283 Views
Learn to use Timer for managing activities over time, set up timers for action events, explore inner classes to access and refer to outer classes easily.
E N D
Processing timer events • Timer • is part of javax.swing • helps manage activity over time • Use it to set up a timer to generate an action event periodically • When a timer event takes place, timer calls • actionPerformed(ActionEvent event) • part of the ActionListener interface (java.awt.event) • Example: TimerTester.java
Inner classes • Inner class • Any class defined inside another • is available to all the methods of the enclosing class • Can access the members of the enclosing class • Can reference the outer class using (Outerclass.this)
Anonymous inner classes • Anonymous classes • Often encountered within a method • Combines the creation of an object with the definition • Requires the inclusion of a semi-colon marking the end • of expression containing the anonymous class • Objects defined inside the method but outside of class • Must be final before used inside anonymous class
Tokenizing strings • When you read a sentence, your mind breaks it into tokens • individual words and punctuation marks that convey meaning. • String method split breaks a String into • component tokens and returns an array of Strings. • Tokens are separated by delimiters • Typically white-space characters • such as space, tab, newline and carriage return. • Other characters can also be used as delimiters to separate tokens.
Regular expressions • A regular expression • a specially formatted String describing a search pattern • useful for validating input • One application is to construct a compiler • Large and complex regular expression are used to this end • If the program code does not match the regular expression • => compiler knows that there is a syntax error
Regular Expressions (cont’d) • String method matches receives a String • specifying the regular expression • matches the contents of the Stringobject parameter • with the regular expression. • and returns a boolean indicating whether • the match succeeded. • A regular expression consists of • literal characters and special symbols.
Character classes • A character class • Is an escape sequence representing a group of chars • Matches a single character in the search object
Ranges • Ranges in characters are determined • By the letters’ integer values • Ex: "[A-Za-z]" matches all uppercase and lowercase letters. • The range "[A-z]" matches all letters • and also matches those characters (such as [ and \) • with an integer value between uppercase A and lowercase z.
Grouping • Parts of regex can be grouped using “()” • Via the “$”, one can refer to a group • Example: • Removing whitespace between a char and “.” or “,” String pattern = "(\\w)(\\s+)([\\.,])"; System.out.println( str.replaceAll(pattern, "$1$3"));
Negative look-ahead • It is • used to exclude a pattern • defined via (?!pattern) • Example: a(?!b) • Matches a if a is not followed by b
Matches Method: Examples • Validating a first name • firstName.matches(“[A-Z][a-zA-Z]*”); • Validating a first name • “([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)” • The character "|" matches the expression • to its left or to its right. • "Hi(John|Jane)" matches both "HiJohn" and "HiJane". • Validating a Zip code • “\\d{5}”;
Split Method: examples publicclass RegexTestStrings { publicstaticfinal String EXAMPLE_TEST = "This is my small example " + "string which I'm going to " + "use for pattern matching."; publicstaticvoid main(String[] args) { System.out.println(EXAMPLE_TEST.matches("\\w.*")); String[] splitString = (EXAMPLE_TEST.split("\\s+")); System.out.println(splitString.length);// Should be 14 for (String string : splitString) { System.out.println(string); } // Replace all whitespace with tabs System.out.println(EXAMPLE_TEST.replaceAll("\\s+", "\t")); } }
RegEx examples • // Returns true if the string matches exactly "true" publicbooleanisTrue(String s){ returns.matches("true"); } • // Returns true if the string matches exactly "true" or "True“ publicboolean isTrueVersion2(String s){ returns.matches("[tT]rue"); } • // Returns true if the string matches exactly "true" or "True" // or "yes" or "Yes" publicbooleanisTrueOrYes(String s){ returns.matches("[tT]rue|[yY]es"); } • // Returns true if the string contains exactly "true" publicbooleancontainsTrue(String s){ returns.matches(".*true.*"); }
RegEx examples (cont’d) • // Returns true if the string consists of three letters publicbooleanisThreeLetters(String s){ returns.matches("[a-zA-Z]{3}");} • // Returns true if the string does not have a number at the beginning publicbooleanisNoNumberAtBeginning(String s){ returns.matches("^[^\\d].*"); } • // Returns true if the string contains arbitrary number of characters //except b publicbooleanisIntersection(String s){ returns.matches("([\\w&&[^b]])*"); }
Pattern and Matcher classes • Java provides java.util.regex • That helps developers manipulate regular expressions • Class Pattern represents a regular expression • Class Matcher • Contains a search pattern and a CharSequence object • If regular expression to be used once • Use static method matches of Pattern class, which • Accepts a regular expression and a search object • And returns a boolean value
Pattern and Matcher classes (cont’d) • If a regular expression is used more than once • Use static method compile of Pattern to • Create a specific Pattern object based on a regular expression • Use the resulting Pattern object to • Call the method matcher, which • Receives a CharSequence to search and returns a Matcher • Finally, use the following methods of the obtained Matcher • find, group, lookingAt, replaceFirst, and replaceAll
Methods of Matcher • The dot character "." in a regular expression • matches any single character except a newline character. • Matcher method find attempts to match • a piece of the search object to the search pattern. • each call to this method starts at the point where the last call ended, so multiple matches can be found. • Matcher method lookingAt performs the same way • except that it starts from the beginning of the search object • and will always find the first match if there is one.
Pattern and Matcher example importjava.util.regex.Matcher; importjava.util.regex.Pattern; publicclassRegexTestPatternMatcher { publicstaticfinal String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching."; publicstaticvoid main(String[] args) { Pattern pattern = Pattern.compile("\\w+"); Matcher matcher = pattern.matcher(EXAMPLE_TEST); while(matcher.find()) { System.out.print("Start index: " + matcher.start()); System.out.print(" End index: " + matcher.end()); System.out.println(matcher.group()); } Pattern replace = Pattern.compile("\\s+"); Matcher matcher2 = replace.matcher(EXAMPLE_TEST); System.out.println(matcher2.replaceAll("\t")); } }
Appendix More examples of Regular Expressions in Java
Validating a username importjava.util.regex.Matcher; importjava.util.regex.Pattern; publicclassUsernameValidator{ private Pattern pattern;private Matcher matcher; privatestaticfinalString USERNAME_PATTERN ="^[a-z0-9_-]{3,15}$"; publicUsernameValidator(){ pattern =Pattern.compile(USERNAME_PATTERN);} /** * Validate username with regular expression * @param username username for validation * @return true valid username, false invalid username */ publicboolean validate(finalString username){ matcher =pattern.matcher(username); returnmatcher.matches(); } } • Examples of usernames that don’t match • mk (too short, min 3 chars); w@lau (“@” not allowed)
Validating image file extension importjava.util.regex.Matcher; importjava.util.regex.Pattern; publicclassImageValidator{ private Pattern pattern; private Matcher matcher; privatestaticfinalString IMAGE_PATTERN ="([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$)"; publicImageValidator(){ pattern =Pattern.compile(IMAGE_PATTERN); } /** * Validate image with regular expression * @param image image for validation * @return true valid image, false invalid image */ publicboolean validate(finalString image){ matcher =pattern.matcher(image);returnmatcher.matches(); } }
Time in 12 Hours Format validator importjava.util.regex.Matcher; importjava.util.regex.Pattern; publicclass Time12HoursValidator{ private Pattern pattern;private Matcher matcher; privatestaticfinalString TIME12HOURS_PATTERN = "(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)"; public Time12HoursValidator(){ pattern = Pattern.compile(TIME12HOURS_PATTERN);} /** * Validate time in 12 hours format with regular expression * @param time time address for validation * @return true valid time fromat, false invalid time format */ publicboolean validate(finalString time){ matcher = pattern.matcher(time);return matcher.matches(); } }
Validating date • Date format validation • (0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d) ( start of group #1 0?[1-9] => 01-09 or 1-9 | ..or [12][0-9] # 10-19 or 20-29 | ..or 3[01] => 30, 31 ) end of group #1 / # followed by a "/" ( # start of group #2 0?[1-9] # 01-09 or 1-9 | # ..or 1[012] # 10,11,12 ) # end of group #2 / # followed by a "/" ( # start of group #3 (19|20)\\d\\d # 19[0-9][0-9] or 20[0-9][0-9] ) # end of group #3