Java Reference
In-Depth Information
To get at the strings for the days of the week, we create a DateFormatSymbols object and call its
getWeekdays() method. This returns an array of eight String objects, the first of which is empty to
make it easy to index using day numbers from 1 to 7. The second element in the array contains
" Sunday ". You can also get the month names using the getMonths() method.
To display the day of the week for the date of birth we call the get() method for the
GregorianCalendar object birthdate , and use the result to index the weekdays[] array. To
determine the appropriate text in the next two output statements, we use the after() and before()
methods for Calendar objects to compare today with the birthday date this year.
Regular Expressions
We have seen some elementary capability for searching strings when we discussed the String class
back in Chapter 4. From Java 1.4, we have had much more sophisticated facilities for analyzing strings
by searching for patterns known as regular expressions . Regular expressions are not unique to Java. Perl
is perhaps better known for its support of regular expressions, many word processors, especially on
Unix, and there are specific utilities for regular expressions too.
So what is a regular expression? A regular expression is simply a string that describes a pattern that is to
be used to search for matches within some other string. It's not simply a passive sequence of characters
to be matched, though. A regular expression is essentially a mini-program for a specialized kind of
computer called a state-machine . This isn't a real machine but a piece of software specifically designed
to interpret a regular expression and analyze a given string based on that.
The regular expression capability in Java is implemented through two classes in the
java.util.regex package: the Pattern class that defines objects that encapsulate regular
expressions, and the Matcher class that defines an object that encapsulates a state-machine that can
search a particular string using a given Pattern object. The java.util.regex package also defines
the PatternSyntaxException class that defines exception objects thrown when a syntax error is
found when compiling a regular expression to create a Pattern object.
Using regular expressions in Java is basically very simple:
1.
You create a Pattern object by passing a string containing a regular expression to the static
compile() method in the Pattern class.
2.
You then obtain a Matcher object, which can search a given string for the pattern, by calling the
matcher() method for the Pattern object with the string that is to be searched as the argument.
3.
You call the find() method (or some other methods as we shall see) for the Matcher object
to search the string.
4. If the pattern is found, you query the matcher object to discover the whereabouts of the
pattern in the string and other information relating to the match.
Search WWH ::




Custom Search