HTML and CSS Reference
Grouping or Clustering. Grouping occurs when a set of characters are enclosed in
parentheses, such as /(ma)/ or /(John|Joe) Brown. If the regular expression pattern is
enclosed in parentheses, a group or subpattern is created. Then instead of the greedy
metacharacters matching on zero, one, or more of the previous single characters, they
can match on the previous subpattern. For example, /(ma)+/ means search for “ma” or
“mama” or “mamama,” and so forth; one or more occurrences of the pattern “ma”. If the
parentheses are removed and the regular expression is /ma+/, we would be searching for
an “m” followed by one or more occurrences of an “a,” such a “ma,” “maaaaaa.” Alter-
nation can also be controlled if the patterns are enclosed in parentheses. In the example,
/(John|Joe) Brown/, the regular expression reads: search for “John Brown” or “Joe
Brown”. The grouping creates a subpattern of either “John” or “Joe” followed by the pat-
tern “Brown”. Without grouping (i.e., /John|John Brown/), the regular expression reads:
search for “John” or “Joe Brown”. This process of grouping characters together is also
called clustering .
<head><title>Grouping or Clustering</title></head>
// Grouping with parentheses
var reg_expression = /^(Sam|Dan|Tom) Robbins/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString) ;// Returns true
// or false
document.write("<b>The regular expression /^(Sam|Dan|Tom)
Robbins/ matched the string\""+ textString +"\".<br />");
By enclosing Sam, Dan, and Tom in parentheses, the alternative now becomes ei-
ther Sam Robbins, Dan Robbins, or Tom Robbins . Without the parentheses, the reg-
ular expression matches Sam , or Dan , or Tom Robbins . The caret metacharacter ^
anchors all of the patterns to the beginning of the line.
The user input is assigned to the variable called textString .
The test() method checks to see if the string contains one of the alternatives: Sam
Robbins or Dan Robbins or Tom Robbins. If it does, true is returned; otherwise, false
is returned. See Figure 17.34.