- •Introduction
- •Who This Book Is For
- •What This Book Covers
- •How This Book Is Structured
- •What You Need to Use This Book
- •Conventions
- •Source Code
- •Errata
- •p2p.wrox.com
- •What Are Regular Expressions?
- •What Can Regular Expressions Be Used For?
- •Finding Doubled Words
- •Checking Input from Web Forms
- •Changing Date Formats
- •Finding Incorrect Case
- •Adding Links to URLs
- •Regular Expressions You Already Use
- •Search and Replace in Word Processors
- •Directory Listings
- •Online Searching
- •Why Regular Expressions Seem Intimidating
- •Compact, Cryptic Syntax
- •Whitespace Can Significantly Alter the Meaning
- •No Standards Body
- •Differences between Implementations
- •Characters Change Meaning in Different Contexts
- •Regular Expressions Can Be Case Sensitive
- •Case-Sensitive and Case-Insensitive Matching
- •Case and Metacharacters
- •Continual Evolution in Techniques Supported
- •Multiple Solutions for a Single Problem
- •What You Want to Do with a Regular Expression
- •Replacing Text in Quantity
- •Regular Expression Tools
- •findstr
- •Microsoft Word
- •StarOffice Writer/OpenOffice.org Writer
- •Komodo Rx Package
- •PowerGrep
- •Microsoft Excel
- •JavaScript and JScript
- •VBScript
- •Visual Basic.NET
- •Java
- •Perl
- •MySQL
- •SQL Server 2000
- •W3C XML Schema
- •An Analytical Approach to Using Regular Expressions
- •Express and Document What You Want to Do in English
- •Consider the Regular Expression Options Available
- •Consider Sensitivity and Specificity
- •Create Appropriate Regular Expressions
- •Document All but Simple Regular Expressions
- •Document What You Expect the Regular Expression to Do
- •Document What You Want to Match
- •Test the Results of a Regular Expression
- •Matching Single Characters
- •Matching Sequences of Characters That Each Occur Once
- •Introducing Metacharacters
- •Matching Sequences of Different Characters
- •Matching Optional Characters
- •Matching Multiple Optional Characters
- •Other Cardinality Operators
- •The * Quantifier
- •The + Quantifier
- •The Curly-Brace Syntax
- •The {n} Syntax
- •The {n,m} Syntax
- •Exercises
- •Regular Expression Metacharacters
- •Thinking about Characters and Positions
- •The Period (.) Metacharacter
- •Matching Variably Structured Part Numbers
- •Matching a Literal Period
- •The \w Metacharacter
- •The \W Metacharacter
- •Digits and Nondigits
- •The \d Metacharacter
- •Canadian Postal Code Example
- •The \D Metacharacter
- •Alternatives to \d and \D
- •The \s Metacharacter
- •Handling Optional Whitespace
- •The \S Metacharacter
- •The \t Metacharacter
- •The \n Metacharacter
- •Escaped Characters
- •Finding the Backslash
- •Modifiers
- •Global Search
- •Case-Insensitive Search
- •Exercises
- •Introduction to Character Classes
- •Choice between Two Characters
- •Using Quantifiers with Character Classes
- •Using the \b Metacharacter in Character Classes
- •Selecting Literal Square Brackets
- •Using Ranges in Character Classes
- •Alphabetic Ranges
- •Use [A-z] With Care
- •Digit Ranges in Character Classes
- •Hexadecimal Numbers
- •IP Addresses
- •Reverse Ranges in Character Classes
- •A Potential Range Trap
- •Finding HTML Heading Elements
- •Metacharacter Meaning within Character Classes
- •The ^ metacharacter
- •How to Use the - Metacharacter
- •Negated Character Classes
- •Combining Positive and Negative Character Classes
- •POSIX Character Classes
- •The [:alnum:] Character Class
- •Exercises
- •String, Line, and Word Boundaries
- •The ^ Metacharacter
- •The ^ Metacharacter and Multiline Mode
- •The $ Metacharacter
- •The $ Metacharacter in Multiline Mode
- •Using the ^ and $ Metacharacters Together
- •Matching Blank Lines
- •Working with Dollar Amounts
- •Revisiting the IP Address Example
- •What Is a Word?
- •Identifying Word Boundaries
- •The \< Syntax
- •The \>Syntax
- •The \b Syntax
- •The \B Metacharacter
- •Less-Common Word-Boundary Metacharacters
- •Exercises
- •Grouping Using Parentheses
- •Parentheses and Quantifiers
- •Matching Literal Parentheses
- •U.S. Telephone Number Example
- •Alternation
- •Choosing among Multiple Options
- •Unexpected Alternation Behavior
- •Capturing Parentheses
- •Numbering of Captured Groups
- •Numbering When Using Nested Parentheses
- •Named Groups
- •Non-Capturing Parentheses
- •Back References
- •Exercises
- •Why You Need Lookahead and Lookbehind
- •The (? metacharacters
- •Lookahead
- •Positive Lookahead
- •Negative Lookahead
- •Positive Lookahead Examples
- •Positive Lookahead in the Same Document
- •Inserting an Apostrophe
- •Lookbehind
- •Positive Lookbehind
- •Negative Lookbehind
- •How to Match Positions
- •Adding Commas to Large Numbers
- •Exercises
- •What Are Sensitivity and Specificity?
- •Extreme Sensitivity, Awful Specificity
- •Email Addresses Example
- •Replacing Hyphens Example
- •The Sensitivity/Specificity Trade-Off
- •Sensitivity, Specificity, and Positional Characters
- •Sensitivity, Specificity, and Modes
- •Sensitivity, Specificity, and Lookahead and Lookbehind
- •How Much Should the Regular Expressions Do?
- •Abbreviations
- •Characters from Other Languages
- •Names
- •Sensitivity and How to Achieve It
- •Specificity and How to Maximize It
- •Exercises
- •Documenting Regular Expressions
- •Document the Problem Definition
- •Add Comments to Your Code
- •Making Use of Extended Mode
- •Know Your Data
- •Abbreviations
- •Proper Names
- •Incorrect Spelling
- •Creating Test Cases
- •Debugging Regular Expressions
- •Treacherous Whitespace
- •Backslashes Causing Problems
- •Considering Other Causes
- •The User Interface
- •Metacharacters Available
- •Quantifiers
- •The @ Quantifier
- •The {n,m} Syntax
- •Modes
- •Character Classes
- •Back References
- •Lookahead and Lookbehind
- •Lazy Matching versus Greedy Matching
- •Examples
- •Character Class Examples, Including Ranges
- •Whole Word Searches
- •Search-and-Replace Examples
- •Changing Name Structure Using Back References
- •Manipulating Dates
- •The Star Training Company Example
- •Regular Expressions in Visual Basic for Applications
- •Exercises
- •The User Interface
- •Metacharacters Available
- •Quantifiers
- •Modes
- •Character Classes
- •Alternation
- •Back References
- •Lookahead and Lookbehind
- •Search Example
- •Search-and-Replace Example
- •Online Chats
- •POSIX Character Classes
- •Matching Numeric Digits
- •Exercises
- •Introducing findstr
- •Finding Literal Text
- •Quantifiers
- •Character Classes
- •Command-Line Switch Examples
- •The /v Switch
- •The /a Switch
- •Single File Examples
- •Simple Character Class Example
- •Find Protocols Example
- •Multiple File Example
- •A Filelist Example
- •Exercises
- •The PowerGREP Interface
- •A Simple Find Example
- •The Replace Tab
- •The File Finder Tab
- •Syntax Coloring
- •Other Tabs
- •Numeric Digits and Alphabetic Characters
- •Quantifiers
- •Back References
- •Alternation
- •Line Position Metacharacters
- •Word-Boundary Metacharacters
- •Lookahead and Lookbehind
- •Longer Examples
- •Finding HTML Horizontal Rule Elements
- •Matching Time Example
- •Exercises
- •The Excel Find Interface
- •Escaping Wildcard Characters
- •Using Wildcards in Data Forms
- •Using Wildcards in Filters
- •Exercises
- •Using LIKE with Regular Expressions
- •The % Metacharacter
- •The _ Metacharacter
- •Character Classes
- •Negated Character Classes
- •Using Full-Text Search
- •Using The CONTAINS Predicate
- •Document Filters on Image Columns
- •Exercises
- •Using the _ and % Metacharacters
- •Testing Matching of Literals: _ and % Metacharacters
- •Using Positional Metacharacters
- •Using Character Classes
- •Quantifiers
- •Social Security Number Example
- •Exercises
- •The Interface to Metacharacters in Microsoft Access
- •Creating a Hard-Wired Query
- •Creating a Parameter Query
- •Using the ? Metacharacter
- •Using the * Metacharacter
- •Using the # Metacharacter
- •Using the # Character with Date/Time Data
- •Using Character Classes in Access
- •Exercises
- •The RegExp Object
- •Attributes of the RegExp Object
- •The Other Properties of the RegExp Object
- •The test() Method of the RegExp Object
- •The exec() Method of the RegExp Object
- •The String Object
- •Metacharacters in JavaScript and JScript
- •SSN Validation Example
- •Exercises
- •The RegExp Object and How to Use It
- •Quantifiers
- •Positional Metacharacters
- •Character Classes
- •Word Boundaries
- •Lookahead
- •Grouping and Nongrouping Parentheses
- •Exercises
- •The System.Text.RegularExpressions namespace
- •A Simple Visual Basic .NET Example
- •The Classes of System.Text.RegularExpressions
- •The Regex Object
- •Using the Match Object and Matches Collection
- •Using the Match.Success Property and Match.NextMatch Method
- •The GroupCollection and Group Classes
- •The CaptureCollection and Capture Class
- •The RegexOptions Enumeration
- •Case-Insensitive Matching: The IgnoreCase Option
- •Multiline Matching: The Effect on the ^ and $ Metacharacters
- •Right to Left Matching: The RightToLeft Option
- •Lookahead and Lookbehind
- •Exercises
- •An Introductory Example
- •The Classes of System.Text.RegularExpressions
- •The Regex Class
- •The Options Property of the Regex Class
- •Regex Class Methods
- •The CompileToAssembly() Method
- •The GetGroupNames() Method
- •The GetGroupNumbers() Method
- •GroupNumberFromName() and GroupNameFromNumber() Methods
- •The IsMatch() Method
- •The Match() Method
- •The Matches() Method
- •The Replace() Method
- •The Split() Method
- •Using the Static Methods of the Regex Class
- •The IsMatch() Method as a Static
- •The Match() Method as a Static
- •The Matches() Method as a Static
- •The Replace() Method as a Static
- •The Split() Method as a Static
- •The Match and Matches Classes
- •The Match Class
- •The GroupCollection and Group Classes
- •The RegexOptions Class
- •The IgnorePatternWhitespace Option
- •Metacharacters Supported in Visual C# .NET
- •Using Named Groups
- •Using Back References
- •Exercise
- •The ereg() Set of Functions
- •The ereg() Function
- •The ereg() Function with Three Arguments
- •The eregi() Function
- •The ereg_replace() Function
- •The eregi_replace() Function
- •The split() Function
- •The spliti() Function
- •The sql_regcase() Function
- •Perl Compatible Regular Expressions
- •Pattern Delimiters in PCRE
- •Escaping Pattern Delimiters
- •Matching Modifiers in PCRE
- •Using the preg_match() Function
- •Using the preg_match_all() Function
- •Using the preg_grep() Function
- •Using the preg_quote() Function
- •Using the preg_replace() Function
- •Using the preg_replace_callback() Function
- •Using the preg_split() Function
- •Supported Metacharacters with ereg()
- •Using POSIX Character Classes with PHP
- •Supported Metacharacters with PCRE
- •Positional Metacharacters
- •Character Classes in PHP
- •Documenting PHP Regular Expressions
- •Exercises
- •W3C XML Schema Basics
- •Tools for Using W3C XML Schema
- •Comparing XML Schema and DTDs
- •How Constraints Are Expressed in W3C XML Schema
- •W3C XML Schema Datatypes
- •Derivation by Restriction
- •Unicode and W3C XML Schema
- •Unicode Overview
- •Using Unicode Character Classes
- •Matching Decimal Numbers
- •Mixing Unicode Character Classes with Other Metacharacters
- •Unicode Character Blocks
- •Using Unicode Character Blocks
- •Metacharacters Supported in W3C XML Schema
- •Positional Metacharacters
- •Matching Numeric Digits
- •Alternation
- •Using the \w and \s Metacharacters
- •Escaping Metacharacters
- •Exercises
- •Introduction to the java.util.regex Package
- •Obtaining and Installing Java
- •The Pattern Class
- •Using the matches() Method Statically
- •Two Simple Java Examples
- •The Properties (Fields) of the Pattern Class
- •The CASE_INSENSITIVE Flag
- •Using the COMMENTS Flag
- •The DOTALL Flag
- •The MULTILINE Flag
- •The UNICODE_CASE Flag
- •The UNIX_LINES Flag
- •The Methods of the Pattern Class
- •The compile() Method
- •The flags() Method
- •The matcher() Method
- •The matches() Method
- •The pattern() Method
- •The split() Method
- •The Matcher Class
- •The appendReplacement() Method
- •The appendTail() Method
- •The end() Method
- •The find() Method
- •The group() Method
- •The groupCount() Method
- •The lookingAt() Method
- •The matches() Method
- •The pattern() Method
- •The replaceAll() Method
- •The replaceFirst() Method
- •The reset() Method
- •The start() Method
- •The PatternSyntaxException Class
- •Using the \d Metacharacter
- •Character Classes
- •The POSIX Character Classes in the java.util.regex Package
- •Unicode Character Classes and Character Blocks
- •Using Escaped Characters
- •Using Methods of the String Class
- •Using the matches() Method
- •Using the replaceFirst() Method
- •Using the replaceAll() Method
- •Using the split() Method
- •Exercises
- •Obtaining and Installing Perl
- •Creating a Simple Perl Program
- •Basics of Perl Regular Expression Usage
- •Using the m// Operator
- •Using Other Regular Expression Delimiters
- •Matching Using Variable Substitution
- •Using the s/// Operator
- •Using s/// with the Global Modifier
- •Using s/// with the Default Variable
- •Using the split Operator
- •Using Quantifiers in Perl
- •Using Positional Metacharacters
- •Captured Groups in Perl
- •Using Back References in Perl
- •Using Alternation
- •Using Character Classes in Perl
- •Using Lookahead
- •Using Lookbehind
- •Escaping Metacharacters
- •A Simple Perl Regex Tester
- •Exercises
- •Index
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