HTML and CSS Reference
In-Depth Information
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 .
EXAMPLE 17.32
<html>
<head><title>Grouping or Clustering</title></head>
<body>
<script type="text/javascript">
// Grouping with parentheses
1
var reg_expression = /^(Sam|Dan|Tom) Robbins/;
2
var textString=prompt("Type a string of text","");
3
var result=reg_expression.test(textString) ;// Returns true
// or false
document.write(result+"<br />");
if (result){
document.write("<b>The regular expression /^(Sam|Dan|Tom)
Robbins/ matched the string\""+ textString +"\".<br />");
}
else{
alert("No Match!");
}
</script>
</body>
</html>
EXPLANATION
1
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.
2
The user input is assigned to the variable called textString .
3
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.
 
Search WWH ::




Custom Search