To create a regular expression, use the provided factory
RegexFactory
.
If J2SE 1.4 (or later) is detected, the factory will create an instance
of
JdkRegex
. Otherwise, it will
create an instance of
Perl5Regex
.
Example:
/** * Returns the domain name of the given e-mail address. * * @param email * the given e-mail address. * @return the domain name of the given e-mail address. * @throws IllegalArgumentException * if the given e-mail address is not valid. */ public String getDomainName(String email) { /* * If we are using J2SE 1.4 (or later) the factory will create an * instance of JdkRegex, otherwise it will create an instance of Perl5Regex. */ Regex regex = RegexFactory.createRegex("^(.+)@(.+)$"); Match match = regex.match(email); if (!match.isSuccessful()) { throw new IllegalArgumentException("E-mail address is not valid"); } String[] groups = match.getGroups(); String domainName = groups[2]; return domainName; }
Note:
RegexFactory
simply chooses
which implementation of
Regex
to create based on the
installed JDK. If you do not want to use the factory, both
JdkRegex
and
Perl5Regex
expose public constructors.