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

Chapter 19

Then click the Custom Level button toward the bottom of the Security tab. The Security Settings window opens. Scroll down the options in the Security Settings window until you come to the scripting options shown in Figure 19-3.

Figure 19-3

If you want to run the examples in this chapter, ensure that the scripting options are enabled, as shown in the preceding figure. Enabling scripting of Java applets is not necessary to run this chapter’s sample code.

Use of regular expressions in JavaScript and JScript depends on regular expression functionality in the RegExp object and the String object. The RegExp object will be described in full, and aspects of the String object relevant to regular expressions will also be described.

The RegExp Object

Patterns can be used with instances of the RegExp object. Those instances can be created in either of two ways:

A variable can have a regular expression pattern assigned to it. For example, the variable myPattern can be assigned the pattern t$ using the following code:

myPattern = /t$/;

A new instance of the RegExp object can be created using a RegExp() constructor:

myPattern = new RegExp(“t$”);

The pattern t$ will match any string that has the final character t.

432

Regular Expressions in JScript and JavaScript

JScript statements can be written one statement to a line without using the statement-terminating semicolon. However, the semicolon is required as a statement terminator in JavaScript. Therefore, all code in this chapter, which aims for cross-language compatibility, will use a semicolon routinely as a statement-terminator character.

The following two examples work identically as far as the end user is concerned. However, one uses the forward-slash syntax and the other uses the RegExp() constructor to assign a RegExp object to a variable. The screenshots in one example are from Internet Explorer and in the other from Firefox. The functionality, as far as the end user is concerned, is the same in each browser.

Try It Out

Creating a RegExp Object Instance Using Forward-Slash Syntax

1.Either type the following code into your favorite editor or open the sample file FinalT.html:

<html>

<head>

<title>Check for Final t in a string</title>

<script language=”javascript” type=”text/javascript”> var myRegExp = /t$/;

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)){

alert(“There is a match!\nThe regular expression pattern is: “ + myRegExp + “.\n The string that you entered was: ‘“ + entry + “‘.”);

}// 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>

2.Open FinalT.html in Internet Explorer. Depending on the file associations you have set on your machine, you may be able to do that simply by double-clicking the file. Alternatively, right-click the file in Windows Explorer and use the Open With option, in which Internet Explorer may already be listed in the context menu. If it’s not listed, click the Choose Program

433

Chapter 19

option and follow the on-screen instructions to locate Internet Explorer. Another alternative is to open Internet Explorer and use the Open option in the File menu to open FinalT.html. Figure 19-4 shows the screen’s appearance when FinalT.html is opened in Internet Explorer.

Figure 19-4

3.Click the Click Here to Enter Text button. Figure 19-5 shows the resulting screen’s appearance.

Figure 19-5

4.Type the character sequence Test in the text box, and click the OK button.

Figure 19-6 shows the screen’s appearance after you click OK. Because the test character sequence, Test, ends in the character t, there is a match for the pattern t$.

Figure 19-6

If you enter a character sequence that does not match, a message indicating that there is no

match will be displayed.

434

Regular Expressions in JScript and JavaScript

5.Click the OK button again, and the message displayed in Figure 19-6 will no longer be displayed. Then click the Click Here to Enter Text button.

6.Type the nonmatching character sequence Tess, and click OK. Figure 19-7 shows the appearance of the resulting message, indicating that there is no match for that test string.

Figure 19-7

How It Works

A global variable, myRegExp, is declared. To that variable is assigned a regular expression pattern, t$, contained between paired forward slashes:

var myRegExp = /t$/;

The pattern t$ matches a single character, t, when it is the last character that the user enters. The paired forward slashes are the delimiters for a regular expression pattern, similarly to the way that paired quotation marks are delimiters for a string.

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 ShowPrompt() function accepts text from the user:

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.”);

Then an if statement uses the Validate() function to check whether or not there is a match for the pattern t$. If there is a match, an alert box is displayed, as specified in the following code:

if (Validate(entry)){

alert(“There is a match!\nThe regular expression pattern is: “ + myRegExp + “.\n

The string that you entered was: ‘“ + entry + “‘.”); } // end if

The arguments to the alert() function concatenate literal message text with the value for the regular expression pattern, contained in the myRegExp variable, and the value entered by the user, contained in the entry variable.

435

Chapter 19

If there is no match, the else clause causes an alert box with alternative text to appear, indicating that there is no match to be displayed:

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

The Validate() function uses the following code to test whether the text entered by the user at the prompt matches the regular expression pattern held in the myRegExp variable:

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

The test() method of the RegExp object takes a string as its argument and tests whether there is a match in the string for the regular expression pattern.

As indicated in the preceding paragraphs, if there is a match, an alert box to that effect is displayed. If there is not, match a message indicating as much is displayed instead.

Next, you will use the RegExp() constructor in the Firefox browser to achieve the same thing.

Try It Out

Using the RegExp() Constructor

1.Open the Firefox browser, if it is installed on your machine. If Firefox is not available, the code will also run on Internet Explorer.

2.From the File menu, select Open; navigate to the file FinalTConstructor.html; and open it. The content is shown here:

<html>

<head>

<title>Check for Final t in a string</title>

<script language=”javascript” type=”text/javascript”> var myRegExp = new RegExp(“t$”);

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)){

alert(“There is a match!\nThe regular expression pattern is: “ + myRegExp + “.\n The string that you entered was: ‘“ + entry + “‘.”);

}// 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

436

Regular Expressions in JScript and JavaScript

} // end function ShowPrompt()

</script>

</head>

<body>

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

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

</body>

</html>

3.Click the Click Here to Enter Text button, and enter the character sequence Test.

4.Click the OK button, and inspect the alert box that is displayed when there is a match, as shown in Figure 19-8.

Figure 19-8

5.Click the OK button to dismiss the alert box; then click the Click Here to Enter Text button and enter the character sequence Test.. Notice that there is a period character as the final character of the test-character sequence.

6.Click the OK button, and inspect the alert box that is displayed.

How It Works

The following code uses the RegExp() constructor to assign a regular expression object containing the pattern t$ to the variable myRegExp:

var myRegExp = new RegExp(“t$”);

The rest of the code functions as described in the preceding Try It Out section. When a lowercase t is the last character entered by the user. there is a match; otherwise, there is not.

Personally, I find the following syntax more convenient to use:

var myRegExp = /t$/;

But the two techniques are functionally equivalent, and if you prefer to use the RegExp() constructor, just substitute that in later examples in this chapter that use the paired-forward-slash syntax.

437