Java Reference
In-Depth Information
Table 14-2. List of the Predefined Regular Expression Character Classes
Predefined
Character Classes
Meaning
. (a dot)
Any character (may or may not match line terminators). Please refer to the section
“Line terminators” in the API documentation of the java.util.regex.Pattern class for
more details.
\d
A digit. Same as [0-9]
\D
A non-digit. Same as [^0-9]
\s
A whitespace character. Same as [ \t\n\x0B\f\r] . The list includes a space, a tab,
a new line, a vertical tab, a form feed, and a carriage return characters.
\S
A non-whitespace character. Same as [^\s]
\w
A word character. Same as [a-zA-Z_0-9] . The list includes lowercase letters, uppercase
letter, underscore, and decimal digits.
\W
A non-word character. Same as [^\w]
If you allow all uppercase and lowercase letters, underscore and digits in your e-mail address validations, the
regular expression to validate e-mail addresses of only three characters would be "\w@\w" . Now you are one step ahead
in your e-mail address validation process. Instead of allowing only A , B , or C in the first part of e-mail (as expressed by
regular expression [ABC]@. ), now you are allowing any word character as the first part as well as second part.
More Powers to Regular Expressions
Until now, you have seen only three methods of the String class using the regular expressions. The package
java.util.regex contains three classes to support the full version of regular expressions. The classes are
Pattern
Matcher
PatternSyntaxException
A Pattern holds the compiled form of a regular expression. The compiled form of a regular expression is its
specialized in-memory representation to facilitate faster string matching. A Matcher associates the string to be
matched with a Pattern and it performs the actual match. A PatternSyntaxException represents an error in a
malformed regular expression.
Compiling Regular Expressions
A Pattern holds the compiled form of a regular expression. It is immutable. It can be shared. It has no public
constructor. The class contains a static compile() method, which returns a Pattern object. The compile() method
is overloaded.
static Pattern compile(String regex)
static Pattern compile(String regex, int flags)
 
Search WWH ::




Custom Search