Java Reference
In-Depth Information
Regular expressions are very powerful features of any programming language. Java
supports regular expressions. If you are familiar with regular expression in Java or Perl,
the following discussion will be easy to follow. The pattern in a regular expression may be
very complex. Typically, the letters and digits in the pattern match the input text literally.
For example, the regular expression
/Java/
will try to match the word
Java
at any
position in the input text. The following code uses the
test()
method to check if a regular
expression matches the input text:
var pattern = new RegExp("Java"); // Same as var pattern = /Java/;
var match = pattern.test("JavaScript");
print(pattern + " matches \"JavaScript\": " + match);
// Perfoms a case-sensitive match that is the default
var match2 = /java/.test("JavaScript");
print("/java/ matches \"JavaScript\": " + match2);
// Performs a case-insensitive match using the i flag
var match3 = /java/i.test("JavaScript");
print("/java/i matches \"JavaScript\": " + match3);
/Java/ matches "JavaScript": true
/java/ matches "JavaScript": false
/java/i matches "JavaScript": true
The
RegExp
object has four properties, as listed in Table
4-17
. The
source
,
global
,
ignoreCase
, and
multiline
properties are read-only, nonenumerable, and
nonconfigurable, and they are set at the time you create the regular expression. The
lastIndex
property is writable, nonenumerable, and nonconfigurable.
Table 4-17.
The List of Methods in the RegExp.prototype Object
Property
Description
source
A string that is the pattern part of the
RegExp
object. If you create a regular
expression using
new RegExp("Java", "gm")
, the
source
property of the
object is set to “Java”
global
It is a Boolean value that is set to
true
if the flag
g
is used,
false
otherwise
ignoreCase
It is a Boolean value that is set to
true
if the flag
i
is used,
false
otherwise
multiline
It is a Boolean value that is set to
true
if the flag
m
is used,
false
otherwise
lastIndex
It is an integer value that specifies the position in the input text where the
next match will start. It is set to zero when the
RegExp
object is created.
It may change automatically when you perform a match or you can
change it in code
Search WWH ::
Custom Search