Java Reference
In-Depth Information
T
ABLE
H.1
Frequently Used Regular Expressions
Regular Expression
Matches
Example
x
a specified character
x
Java
matches
Java
.
any single character
Java
matches
J..a
(ab|cd)
ab or cd
ten
matches
t(en|im)
[abc]
a, b, or c
Java
matches
Ja[uvwx]a
[^abc]
any character except
a, b, or c
Java
matches
Ja[^ars]a
[a-z]
a through z
Java
matches
[A-M]av[a-d]
[^a-z]
any character except
a through z
Java
matches
Jav[^b-d]
[a-e[m-p]]
a through e or
m through p
Java
matches
[A-G[I-M]]av[a-d]
[a-e&&[c-p]]
intersection of a-e
with c-p
Java
matches
[A-P&&[I-M]]av[a-d]
\d
a digit, same as [0-9]
Java2
matches
"Java[\\d]"
\D
a non-digit
$Java
matches
"[\\D][\\D]ava"
\w
a word character
Java1
matches
"[\\w]ava[\\w]"
\W
a non-word character
$Java
matches
"[\\W][\\w]ava"
\s
a whitespace character
"Java 2"
matches
"Java\\s2"
\S
a non-whitespace char
Java
matches
"[\\S]ava"
p
*
zero or more
occurrences of pattern
p
aaaabb
matches
"a*bb"
ababab
matches
"(ab)*"
p
+
one or more occurrences
of pattern
p
a
matches
"a+b*"
able
matches
"(ab)+.*"
p
?
zero or one occurrence of
pattern
p
Java
matches
"J?Java"
Java
matches
"J?ava"
p
{n}
exactly n occurrences of
pattern
p
Java
matches
"Ja{1}.*"
Java
does not match
".{2}"
p
{n,}
at least n occurrences of
pattern
p
aaaa
matches
"a{1,}"
a
does not match
"a{2,}"
p
{n,m}
between n and m occur-
rences (inclusive)
aaaa
matches
"a{1,9}"
abb
does not match
"a{2,9}bb"
Note
A word character is any letter, digit, or the underscore character. So
\w
is the same
as
[a-z[A-Z][0-9]_]
or simply
[a-zA-Z0-9_]
, and
\W
is the same as
[^a-zA-Z0-9_]
.
Note
The last six entries
*
,
+
,
?
,
{n}
,
{n,}
, and
{n, m}
in Table H.1 are called
quantifiers
that specify how many times the pattern before a quantifier may repeat. For example,
A*
matches zero or more
A
's,
A+
matches one or more
A
's,
A?
matches zero or one
A
's,
A{3}
matches exactly
AAA
,
A{3,}
matches at least three
A
's, and
A{3,6}
matches between
3 and 6
A
's.
*
is the same as
{0,}
,
+
is the same as
{1,}
, and
?
is the same as
{0,1}
.
quantifier
Search WWH ::
Custom Search