Java Reference
In-Depth Information
Special Characters Used in Regular Expressions
character
exaMples
function
/n/
matches
n
;
/\n/
matches a
linefeed character;
/^/
matches the
start of a line; and
/\^/
matches
^
.
For characters that are by default
treated as normal characters, the
backslash indicates that the next
character is to be interpreted with a
special value. For characters that are
usually treated as special characters,
the backslash indicates that the next
character is to be interpreted as a
normal character.
\
/^A/
matches the first but not the
second
A
in “
A man called Adam
.”
Matches the start of a line or of the
input
.
^
/r$/
matches only the last
r
in
“
horror
.”
Matches the end of a line or of the
input
.
$
/ro*/
matches
r
in “
right
,”
ro
in
“
wrong
,” and “
roo
” in “
room
.”
Matches the preceding character
zero or more times.
*
/l+/
matches
l
in “
life
,”
ll
in
“
still
,” and
lll
in “
stilllife
.”
Matches the preceding character one
or more times. For example,
/a+/
matches the
a
in “
candy
” and all the
a
ls in “
caaaaaaandy
.”
+
/Smythe?/
matches “
Smyth
” and
“
Smythe
.”
Matches the preceding character
once or zero times.
?
/.b/
matches the second but not the
first
ob
in “
blob
.”
Matches any character apart from the
newline character.
.
/(Smythe?)/
matches “
Smyth
” and
“
Smythe
” in “
John Smyth and Rob
Smythe
” and allows the substrings
to be retrieved as
RegExp.$1
and
RegExp.$2
, respectively.
Matches
x
and remembers the
match. The matched substring
can be retrieved from the elements
of the array that results from
the match, or from the
RegExp
object's properties
$1
,
$2
…
$9
, or
lastParen
.
(x)
/Smith|Smythe/
matches “
Smith
”
and “
Smythe
.”
Matches either
x
or
y
(where
x
and
y
are blocks of characters).
x|y
/l{2}/
matches
ll
in “
still
” and
the first two
l
ls in “
stilllife
.”
Matches exactly
n
instances of the
preceding character (where
n
is a
positive integer).
{n}