img
Here, newStr specifies the new character sequence that will replace the ones that match the
pattern. The updated input sequence is returned as a string.
Regular Expression Syntax
Before demonstrating Pattern and Matcher, it is necessary to explain how to construct a
regular expression. Although no rule is complicated by itself, there are a large number of
them, and a complete discussion is beyond the scope of this chapter. However, a few of the
more commonly used constructs are described here.
In general, a regular expression is comprised of normal characters, character classes
(sets of characters), wildcard characters, and quantifiers. A normal character is matched
as-is. Thus, if a pattern consists of "xy", then the only input sequence that will match it is
"xy". Characters such as newline and tab are specified using the standard escape sequences,
which begin with a \. For example, a newline is specified by \n. In the language of regular
expressions, a normal character is also called a literal.
A character class is a set of characters. A character class is specified by putting the
characters in the class between brackets. For example, the class [wxyz] matches w, x, y, or z.
To specify an inverted set, precede the characters with a ^. For example, [^wxyz] matches
any character except w, x, y, or z. You can specify a range of characters using a hyphen.
For example, to specify a character class that will match the digits 1 through 9, use [1-9].
The wildcard character is the . (dot) and it matches any character. Thus, a pattern that
consists of "." will match these (and other) input sequences: "A", "a", "x", and so on.
A quantifier determines how many times an expression is matched. The quantifiers are
shown here:
+
Match one or more.
*
Match zero or more.
?
Match zero or one.
For example, the pattern "x+" will match "x", "xx", and "xxx", among others.
One other point: In general, if you specify an invalid expression, a PatternSyntaxException
will be thrown.
Demonstrating Pattern Matching
The best way to understand how regular expression pattern matching operates is to work
through some examples. The first, shown here, looks for a match with a literal pattern:
// A simple pattern matching demo.
import java.util.regex.*;
class RegExpr {
public static void main(String args[]) {
Pattern pat;
Matcher mat;
boolean found;
pat = Pattern.compile("Java");
mat = pat.matcher("Java");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home