Computer science: Perl regex: grouping with parentheses

Self-tutoring about computer science: the tutor mentions using parentheses in Perl regular expressions to form groups.

A useful feature of regular expressions is the optional use of parentheses. There are numerous reasons to use them, but one is to report parts of the match.

Consider the following:

$strng=”Hehe_12345_68d-910″;

if($strng=~m/(hehe(_[\d]+_)([\d]+d)(-[d]+))/i){

print “$1\n$2\n$3\n$4\n”;

}
else{

print “no match”;
}

The output would be (assuming no typos:)

Hehe_12345_68d-910
_12345_
68d
-910

$1 denotes the contents of the first set of parentheses in the matching pattern, $2 the second, and so on. The groupings can be used to organize the output from the match.

Source:

perldoc.perl.org

roberts perl tutorial

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply