By using parentheses creatively in a regular expression a sub-pattern can be marked out such that when a match occurs, that sub-pattern can be extracted.
Here is a pattern that matches a date format:
/[0-9]{2}-[a-zA-Z]{3}-[0-9]{4}/
We might want to extract just the month name. We can place parentheses around that so it can be extracted later. Like this:
/[0-9]{2}-([a-zA-Z]{3})-[0-9]{4}/
The example shows how this works:
<HTML> <HEAD> </HEAD> <BODY> <SCRIPT> // Make the RegExp from a literal myRegExp = /[0-9]{2}-([a-zA-Z]{3})-[0-9]{4}/; // Create the input search string myString = "01-Jan-1954"; // Run the search myArray = myRegExp.exec(myString); // How many items are there in the array document.write(myArray.length); document.write("<BR>"); // Display the source string document.write(myArray[0]); document.write("<BR>"); // Display the month name sub-match document.write(myArray[1]); document.write("<BR>"); </SCRIPT> </BODY> </HTML>
Prev | Home | Next |
RegExp pattern - repetition | Up | Regular expression |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |