Java Reference
In-Depth Information
Resetting the Matcher
If you have finished matching a pattern against input text and you want to restart matching from the beginning of
the input text again, you need to use the reset() method of the Matcher class. After a call to the reset() method,
the next call to match a pattern will start from the beginning of the input text. The reset() method is overloaded.
Another version allows you to associate a different input text with the pattern. These two versions of reset() methods
allow you to reuse any existing instance of the Matcher class if your pattern remains the same. This enhances the
performance of your program by avoiding the need to recreate a new Matcher object to perform matches against the
same pattern.
Final Words on E-mail Validations
You now have learned the major parts of regular expressions. You are ready to complete your e-mail address
validation example. Your e-mail addresses will be validated against the following rules:
name@domain .
All e-mail addresses will be of the form
a-z, A-Z, 0-9 ).
The name part must start with an alphanumeric character (
The name part must have at least one character.
a-z, A-Z, 0-9 ), underscore,
The name part may have any alphanumeric character (
hyphen, or dot.
The dot in the domain part must contain at least one dot.
The dot in domain name must be preceded and followed by at least one alphanumeric
character.
You should also be able to refer to the name and the domain parts using group numbers. This
validation states that you place name and domain part as groups inside the regular expression.
The following regular expression will match an e-mail address according to the above rules. Group 1 is the name
part whereas group 2 is the domain part.
([a-zA-Z0-9]+[\\w\\-.]*)@([a-zA-Z0-9]+\\.[a-zA-Z0-9\\-.]+)
The more validations you add, the more complex the regular expression. Readers are encouraged to add some
more validations for e-mail addresses and modify the above regular expression accordingly. This regular expression
allows two consecutive dots in the domain part. How would you prevent that?
Find-and-Replace Using Regular Expressions
Find-and-replace is a very powerful technique supported by regular expressions in Java. Sometimes you may be
required to find a pattern and replace it depending upon the text it matches; that is, the replacement text is decided
based on some conditions. The Java regular expression designers visualized this need and they have included two
methods in the Matcher class that let you accomplish this task:
Matcher appendReplacement(StringBuffer sb, String replacement)
StringBuffer appendTail(StringBuffer sb)
 
Search WWH ::




Custom Search