Java Reference
In-Depth Information
A PPENDIX H
Regular Expressions
Often you need to write the code to validate user input such as to check whether the input is
a number, a string with all lowercase letters, or a social security number. How do you write
this type of code? A simple and effective way to accomplish this task is to use the regular
expression.
A regular expression (abbreviated regex ) is a string that describes a pattern for matching
a set of strings. Regular expression is a powerful tool for string manipulations. You can use
regular expressions for matching, replacing, and splitting strings.
regular expression
H.1 Matching Strings
Let us begin with the matches method in the String class. At first glance, the matches
method is very similar to the equals method. For example, the following two statements
both evaluate to true .
matches
"Java" .matches( "Java" );
"Java" .equals( "Java" );
However, the matches method is more powerful. It can match not only a fixed string, but
also a set of strings that follow a pattern. For example, the following statements all evaluate
to true .
"Java is fun" .matches( "Java.*" )
"Java is cool" .matches( "Java.*" )
"Java is powerful" .matches( "Java.*" )
"Java.*" in the preceding statements is a regular expression. It describes a string pattern
that begins with Java followed by any zero or more characters. Here, the substring .* matches
any zero or more characters.
H.2 Regular Expression Syntax
A regular expression consists of literal characters and special symbols. Table H.1 lists some
frequently used syntax for regular expressions.
Note
Backslash is a special character that starts an escape sequence in a string. So you need
to use \\d in Java to represent \d .
Note
Recall that a whitespace character is ' ' , '\t' , '\n' , '\r' , or '\f' . So \s is the
same as [ \t\n\r\f] , and \S is the same as [^ \t\n\r\f] .
1278
 
 
 
Search WWH ::




Custom Search