RegExp pattern - sub-patterns (Definition)

When a pattern matches, it is possible to extract a portion of that for re-use.

Availability:

ECMAScript edition - 3

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:

Example code:

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

See also:RegExp pattern, RegExp pattern - grouping, RegExp pattern - references

Cross-references:

ECMA 262 edition 3 - section - 15.10.1