Java Reference
In-Depth Information
Caution
Do not use spaces in the repeat quantifiers. For example,
A{3,6}
cannot be written as
A{3, 6}
with a space after the comma.
Note
You may use parentheses to group patterns. For example,
(ab){3}
matches
ababab
,
but
ab{3}
matches
abbb
.
Let us use several examples to demonstrate how to construct regular expressions.
Example 1
The pattern for social security numbers is
xxx-xx-xxxx
, where
x
is a digit. A regular
expression for social security numbers can be described as
[\\d]{
3
}-[\\d]{
2
}-[\\d]{
4
}
For example,
"111-22-3333".matches("[\\d]{3}-[\\d]{2}-[\\d]{4}")
returns
true
.
"11-22-3333".matches("[\\d]{3}-[\\d]{2}-[\\d]{4}")
returns
false
.
Example 2
An even number ends with digits
0
,
2
,
4
,
6
, or
8.
The pattern for even numbers can be
described as
[\\d]*[
02468
]
For example,
"123".matches("[\\d]*[02468]")
returns
false
.
"122".matches("[\\d]*[02468]")
returns
true
.
Example 3
The pattern for telephone numbers is
(xxx) xxx-xxxx
, where
x
is a digit and the first
digit cannot be zero. A regular expression for telephone numbers can be described as
\\([
1
-
9
][\\d]{
2
}\\) [\\d]{
3
}-[\\d]{
4
}
Note that the parentheses symbols
(
and
)
are special characters in a regular expression for
grouping patterns. To represent a literal
(
or
)
in a regular expression, you have to use
\\(
and
\\)
.
For example,
"(912) 921-2728".matches("\\([1-9][\\d]{2}\\) [\\d]{3}-[\\d]{4}")
returns
true
.
"921-2728".matches("\\([1-9][\\d]{2}\\) [\\d]{3}-[\\d]{4}")
returns
false
.
Example 4
Suppose the last name consists of at most 25 letters and the first letter is in uppercase. The
pattern for a last name can be described as
[A-Z][a-zA-Z]{
1
,
24
}
Note that you cannot have arbitrary whitespace in a regular expression. For example,
[A-Z]
[a-zA-Z]{
1, 24
}
would be wrong.
Search WWH ::
Custom Search