Returning an array using exec
varpattern=/^[a-z]+\s[0-9]{4}$/; varStr= ' Google 2012 '; Alert (pattern.exec (str)); //returns an array that contains a stringvarpattern=/^[a-z]+/;//match only to lettersvarStr= ' Google 2012 '; Alert (pattern.exec (str)); //returns only a string array of Googlevarpattern=/^ ([a-z]+) \s ([0-9]{4}) $/;//Use the GroupingvarStr= ' Google 2012 '; varA=pattern.exec (str); alert (a.length); //returns the length of a 3Alert (a[0]);//returns the entire string that matches toAlert (a[1]);//returns a string that matches the first groupedAlert (a[2]);//returns the word that matches to the second grouping
Capturing groups and non-capturing groupings
1 varpattern=/(\d+) ([A-z])/;//This is called the capturing group, and all the groupings are captured to return2 varStr= ' 123ABC '; 3 varA=pattern.exec (str);4Alert (a[0]);//returns the entire string matched to 123a5Alert (a[1]);//returns the string that matches to the first grouped 1236Alert (a[2]);//returns a string that matches to the second grouping7 8 varpattern=/(\d+) (?: [A-z])/;//non-capturing groupings, as long as the returned groupings are not required to be captured plus?:9 varStr= ' 123ABC '; TenAlert (pattern.exec (str));
Nested groupings
1 var pattern=/(a? ( B? (c?))) /; // nesting groups, getting inside out 2 var str= ' abc '; 3 Alert (pattern.exec (str)); 4 // first step: a[0], the entire match to the string ABC 5 // Step Two: a[1], match the first group (a? ( B? (c?))), ABC6// Third step: a[2], matching the second group (b? ( C?)), BC7// Fourth step: a[3], match the third group (c?) ,
Prospective capture
1 var pattern=/goo (? =gle)/; // goo must be gle to return to goo, it is important to note that Goo is returned, not Google 2 var str= ' Google '; 3 alert (pattern.exec (str));
JavaScript Regular expression pattern matching (4)--using Exec to return arrays, capturing groups and non-capturing groupings, nested groupings