Java Reference
In-Depth Information
You can also create regular expressions using regular expression literals. The syntax
to use a regular expression literal is:
/pattern/flags
The following are examples of creating regular expressions using the regular
expression literals:
var pattern1 = /Java/gm; // The same as new RegExp("Java", "gm")
var pattern2 = /Nashorn/; // The same as new RegExp("Nashorn")
A regular expression literal is converted to a
RegExp
object every time is it evaluated.
According to this rule, if two regular expression literals with the same contents appear in
the same program, they will evaluate to two different
RegExp
objects, as shown:
// pattern1 and pattern2 have the same contents, but they evaluate to
// different RegExp objects
var pattern1 = /Java/gm;
var pattern2 = /Java/gm;
// Prints false in both cases
print(pattern1 === pattern2);
print(/Nashoern/ === /Nashorn/);
The
RegExp.prototype
object contains three methods as listed in Table
4-16
.
The
test()
method is a specialized case of the
exec()
method. The
toString()
method
returns the string form of the regular expression. You only need to learn the
exec()
method in detail.
Table 4-16.
The List of Methods in the RegExp.prototype Object
Method
Description
exec(string)
Performs a match on
string
against the regular expression. Returns
an
Array
object containing the results of the match or
null
if there
was no match
test(string)
Calls the
exec(string)
method. Returns
true
if the
exec()
method
returns not
null
,
false
otherwise. Use this method instead of the
exec()
method if you care about only to know whether there is a
match
toString()
Returns a string of the form
/pattern/gim
, where
gim
is the flags that
were specified when the
RegExp
object was created
Search WWH ::
Custom Search