Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning Regular Expressions 2005.pdf
Скачиваний:
95
Добавлен:
17.08.2013
Размер:
25.42 Mб
Скачать

Chapter 19

Attributes of the RegExp Object

The following code (which you have just seen) assigns a pattern t$ to the variable myRegExp using the default settings of the RegExp object:

var myRegExp = /t$/;

The general form of such an assignment statement allows attributes of the RegExp object to be expressed. The general form is

var myVariable = /pattern/attributes

where pattern is a regular expression pattern and attributes is a string that can contain any of the characters m, g, and i. The attribute m indicates multiline matching, the attribute i indicates case-insensitive matching, and the attribute g indicates global matching. In multiline matching, the ^ and $ metacharacters match the positions at the beginning and end of the whole test text, even if it spreads across multiple lines.

If you prefer using the RegExp() constructor, the syntax is as follows:

var myVariable = new RegExp(pattern, attributes)

The m, g, and i attributes correspond to three of the properties of the RegExp object. The RegExp object’s global property indicates whether or not the g attribute has been specified. The RegExp object’s ignoreCase property corresponds to the i attribute having been specified. The RegExp object’s multiline property indicates whether the m attribute has been sent.

The Other Properties of the RegExp Object

In addition to the global, ignoreCase, and multiline properties, the RegExp object has additional properties.

The lastIndex property indicates the position of the last match. The lastIndex property is used when finding multiple matches in a string. The source property holds the source text for the regular expression — in other words, it holds the regular expression pattern.

The example file NumericDigitsOthersAllowed.html shows how you can access the properties just mentioned. The code for NumericDigitsOthersAllowed.html is shown here:

<html>

<head>

<title>RegExp Object Properties</title>

<script language=”javascript” type=”text/javascript”> var myRegExp = /\d+/;

function Validate(entry){ return myRegExp.test(entry); } // end function Validate()

function ShowPrompt(){

var entry = prompt(“This script tests for matches for the regular expression pattern: “ + myRegExp + “.\nType in a string and click on the OK button.”, “Type your text here.”);

if (Validate(entry)){

438

Regular Expressions in JScript and JavaScript

displayString = “”;

displayString += “There is a match!\nThe regular expression pattern is: “ + myRegExp + “.\nThe string that you entered was: ‘“ + entry +”\n”; displayString += “The global property contained: “ + myRegExp.global + “\n”; displayString += “The ignoreCase property contained: “ + myRegExp.ignoreCase + “\n”;

displayString += “The multiline property contained: “ + myRegExp.multiline + “\n”; displayString += “The source property contained: “ + myRegExp.source + “\n”; displayString += “The lastIndex property contained: “ + myRegExp.lastIndex; alert(displayString);

}// end if else{

alert(“There is no match in the string you entered.\n” + “The regular expression pattern is “ + myRegExp + “\n” + “You entered the string: ‘“ + entry + “‘.” );

}// end else

}// end function ShowPrompt()

</script>

</head>

<body>

<form name=”myForm”> <br />

<button type=”Button” onclick=”ShowPrompt()”>Click here to enter text.</button> </form>

</body>

</html>

Try It Out

Explore RegExp Object Properties

1.Open the file NumericDigitsOthersAllowed.html in Internet Explorer.

2.Click the Click Here to Enter Text button, and enter the text Hello 99 in the text box.

3.Click the OK button, and inspect the information displayed in the alert box, as shown in Figure 19-9.

Figure 19-9

4.Click the OK button to dismiss the alert box, click the Click Here to Enter Text button again, and enter the text 99 Hello in the text box.

439

Chapter 19

5.Click the OK button, and inspect the information displayed in the alert box, as shown in Figure 19-10.

Figure 19-10

6.Compare the appearances of Figure 19-9 (after the sample text Hello 99 was entered) and Figure 19-10 (after the sample text 99 Hello was entered). Notice the difference in the values of the lastIndex property of the RegExp object.

How It Works

The variable myRegExp is declared as a global variable:

var myRegExp = /\d+/;

It is assigned a RegExp object containing the pattern \d+, which will match one or more numeric digits. When the Click Here to Enter Text button is clicked, the ShowPrompt() function is called.

<button type=”Button” onclick=”ShowPrompt()”>Click here to enter text.</button>

The Validate() function is called from the ShowPrompt() function:

function Validate(entry){ return myRegExp.test(entry); } // end function Validate()

If the entry variable is validated, a display string is built up that contains information about the properties of the RegExp object assigned to the variable myRegExp:

if (Validate(entry)){ displayString = “”;

displayString += “There is a match!\nThe regular expression pattern is: “ + myRegExp + “.\nThe string that you entered was: ‘“ + entry +”\n”; displayString += “The global property contained: “ + myRegExp.global + “\n”; displayString += “The ignoreCase property contained: “ + myRegExp.ignoreCase +

“\n”;

displayString += “The multiline property contained: “ + myRegExp.multiline + “\n”; displayString += “The source property contained: “ + myRegExp.source + “\n”; displayString += “The lastIndex property contained: “ + myRegExp.lastIndex; alert(displayString);

} // end if

440

Regular Expressions in JScript and JavaScript

Because the myRegExp variable was created with none of the associations specified, each of the global, ignoreCase, and multiline properties contains the Boolean value false.

The source property contains the value of the pattern, \d+, which was contained in the assignment statement for the myRegExp variable.

The lastIndex property contains the value of the character position following the previous match. When the test text was Hello 99, the value of the lastIndex property was 8, because the match (the character sequence 99) consisted of character positions 6 and 7. When the test text was 99 Hello, the value of the lastIndex property was 2, because the match, 99, consisted of character positions 0 and 1, because indexing starts at 0.

The test() Method of the RegExp Object

The test() method of the RegExp object tests whether or not a string matches a pattern. If there is at least one match, the test() method returns the Boolean value true. If there is no match, the test() method returns the Boolean value false.

You saw in the preceding example situations that the value true was returned, because both test character sequences, Hello 99 and 99 Hello, contained at least one numeric digit and therefore matched the pattern \d+, which matches one or more numeric digits.

If you enter a character sequence that contains no numeric digit, the value returned by the test() method when matching the pattern \d+ will be the Boolean value false.

The exec() Method of the RegExp Object

The exec() method of the RegExp object is powerful, flexible, and potentially confusing.

First, let’s look at using the exec() method when the pattern is used with the g attribute. In other words, the value of the global property of the RegExp object will contain the Boolean value true.

Try It Out

With global Property true

The test file, RegExpExecExample.html, contains the following markup and code:

<html>

<head>

<title>RegExp exec() Method Example with global attribute set.</title> <script language=”javascript” type=”text/javascript”>

var myRegExp = /\sthe/ig; var entry;

function PatternProcess(entry){ var displayString = “”;

while ((result = myRegExp.exec(entry)) != null ){ displayString += “Matched ‘“ + result;

displayString += “‘ at position “ + result.index + “\n”;

displayString += “The next match attempt begins at position “ + myRegExp.lastIndex; alert(displayString);

displayString = “”;

}// end while loop

}// end function Process(entry)

441

Chapter 19

function ShowPrompt(){

entry = prompt(“This script tests for matches for the regular expression pattern: “ + myRegExp + “.\nType in a string and click on the OK button.”, “Type your text here.”);

PatternProcess(entry);

} // end function ShowPrompt()

</script>

</head>

<body>

<form name=”myForm”> <br />

<button type=”Button” onclick=”ShowPrompt()”>Click here to enter text.</button> </form>

</body>

</html>

1.Open RegExpExecExample.html in Internet Explorer, and click the Click Here to Enter Text button.

2.In the text box, enter the following text: Hello there, the theatre is nice., which contains three matches for the pattern \sthe.

Figure 19-11 shows the sample text entered in the prompt dialog box.

Figure 19-11

3.Click the OK button, and inspect the alert box that is displayed, as shown in Figure 19-12. Notice that the matched text is the, which starts at position 6. Given the test string Hello there, the theatre is nice., I hope you can see that the match the is the first three characters of there.

Figure 19-12

4.Click the OK button, and inspect the next alert box that is displayed, as shown in Figure 19-13. Notice that the position of the matched text now begins at position 12, which indicates that the matching the is the word the in the test string.

442

Regular Expressions in JScript and JavaScript

Figure 19-13

5.Click the OK button, and inspect the next alert box that is displayed, as shown in Figure 19-14. Notice that the position of the matched text now begins at position 16, which indicates that the matching the is the first three letters of theatre in the test string.

Figure 19-14

How It Works

As written, the code will display all matches in separate alert boxes. If there is no match, no message is displayed.

The pattern to be matched is \sthe, which is a whitespace character followed by the character sequence the.

The test string, Hello there, the theatre is nice., contains three character sequences that match the pattern \sthe.

The first match is the space character after the word Hello followed by the character sequence the in the word there. Numbering of character positions starts at 0. Position 5 is the position before the first matching character, which is a space character. Any further matching would continue after the e of the at position 9.

The second match is the space character after the comma following the word there. The following character sequence the is the word the.

The third match is the space character after the word the, followed by the first three characters of the word theatre.

When the exec() method of the RegExp object is used in a nonglobal matching process, it matches only once. It returns parts of the matching character sequence that correspond to parts of the pattern that are within parentheses in an array. It is, perhaps, easier to demonstrate what is returned, rather than attempt to describe it in isolation.

443

Chapter 19

Try It Out

The exec() Method in Nonglobal Matching

The sample file, RegExpExecNonGlobal.html, is shown here:

<html>

<head>

<title>RegExp exec() Method Example with no global attribute.</title> <script language=”javascript” type=”text/javascript”>

var myRegExp = /((A|B)(\d{3}))/i; var entry;

function PatternProcess(entry){ var displayString = “”;

result = myRegExp.exec(entry); for (n=0; n<5; n++){

displayString += “Matched ‘“ + result[n]; displayString += “‘ in result[“ + n + “].\n”; } // end for loop

alert(displayString);displayString = “”; } // end function Process(entry)

function ShowPrompt(){

entry = prompt(“This script tests for matches for the regular expression pattern: “ + myRegExp + “.\nType in a string and click on the OK button.”, “Type your text here.”);

PatternProcess(entry);

} // end function ShowPrompt()

</script>

</head>

<body>

<form name=”myForm”> <br />

<button type=”Button” onclick=”ShowPrompt()”>Click here to enter text.</button> </form>

</body>

</html>

1.Open RegExpExecNonGlobal.html in Internet Explorer, and click the Click Here to Enter Text button.

2.Enter a part number, A234, in the text box in the prompt dialog box, and click the OK button.

3.Inspect the alert box that is displayed, as shown in Figure 19-15.

Figure 19-15

444

Regular Expressions in JScript and JavaScript

How It Works

In result[0], the whole of the matching character sequence is returned — in this case, A234.

In result[1], the matching character sequence contained in the outermost parentheses is returned. In this example, that is also A234.

In result[2], the matching character sequence contained in the next set of nested parentheses is returned. In this case, that is A.

In result[3], the matching character sequence contained in the next set of nested parentheses is returned. In this case, that is 234.

The array element result[4] was added to demonstrate that the value undefined is returned when there is no further pair of matching parentheses.

The next Try It Out section puts the two situations together to look in more detail at using parentheses and global matching.

Try It Out

Parentheses and Global Matching with exec()

The test file, RegExpExecExample2.html, is shown here:

<html>

<head>

<title>RegExp exec() Method Example with global attribute set.</title> <script language=”javascript” type=”text/javascript”>

var myRegExp = /((A|B|C)(\d{3}))/ig; var entry;

function PatternProcess(entry){ var displayString = “”;

while ((result = myRegExp.exec(entry)) != null ){ displayString += “Matched ‘“ + result;

displayString += “‘ at position “ + result.index + “\n”;

displayString += “The next match attempt begins at position “ + myRegExp.lastIndex + “\n”;

displayString += “The whole matching string is “ + result[0] + “\n”; displayString += “The content of the outer parentheses is “ + result[1] + “\n”; displayString += “The content of the first nested parentheses is “ + result[2] + “\n”;

displayString += “The content of the second nested parentheses is “ + result[3] + “\n”;

alert(displayString); displayString = “”;

}// end while loop

}// end function Process(entry)

function ShowPrompt(){

entry = prompt(“This script tests for matches for the regular expression pattern: “ + myRegExp + “.\nType in a string and click on the OK button.”, “Type your text here.”);

PatternProcess(entry);

} // end function ShowPrompt()

445

Chapter 19

</script>

</head>

<body>

<form name=”myForm”> <br />

<button type=”Button” onclick=”ShowPrompt()”>Click here to enter text.</button> </form>

</body>

</html>

The matching is global, as indicated by the g attribute in the declaration of the myRegExp variable. It also includes parentheses.

1.Open RegExpExecExample2.html in Internet Explorer, and click the Click Here to Enter Text button.

2.Enter the test text A123, B456, C789 in the text box, and click the OK button.

3.Inspect the results displayed in the first alert box, as shown in Figure 19-16. (The results will be discussed in the How It Works section that follows.)

Figure 19-16

4.Click the OK button to dismiss the first alert box, and inspect the results displayed in the second alert box, as shown in Figure 19-17.

Figure 19-17

5.Click the OK button to dismiss the second alert box, and inspect the results displayed in the third alert box, as shown in Figure 19-18.

446

Regular Expressions in JScript and JavaScript

Figure 19-18

How It Works

The myRegExp variable is declared in the following statement:

var myRegExp = /((A|B|C)(\d{3}))/ig;

This pattern, ((A|B|C)(\d{3})), will match character sequences that begin with A, B, or C followed by three numeric digits. Not all the parentheses are necessary, but they help illustrate what the exec() method returns in the array of results when parentheses are present.

The following test string contains three matches for the pattern ((A|B|C)(\d{3})): A123, B456, and

C789:

A123, B456, C789

First, look in detail at what is displayed in the first alert box, which you can inspect in Figure 19-16.

The information displayed in that alert box is built up in the following code:

displayString += “Matched ‘“ + result;

displayString += “‘ at position “ + result.index + “\n”;

displayString += “The next match attempt begins at position “ + myRegExp.lastIndex + “\n”;

displayString += “The whole matching string is “ + result[0] + “\n”;

displayString += “The content of the outer parentheses is “ + result[1] + “\n”; displayString += “The content of the first nested parentheses is “ + result[2] + “\n”;

displayString += “The content of the second nested parentheses is “ + result[3] + “\n”;

It is displayed using the following code:

alert(displayString);

The first line of the alert box displays each part of the result array separated by commas. As you can see in Figure 19-16, it reads Matched ‘A123, A123, A, 123’ at position 0. The commas separate the content of result[0], result[1], result[2], and result[3]. Matching begins at position 0.

447