Home » Perl Basics » 10 - Regular Expressions
10

Grouping

Grouping is used to decompose any variables into groups.

Grouping is used to decompose any variables into groups.
Exemple :

  $variable1 =” I am 33 years young, not 33 years old ”
  $variable1 =~ / (\w)\s (\w\w)\s (\d\d)/;
  print “$1 $2 $3” ‘, “/n”;

$1 $2 etc… are the variable created by Perl when you use groupings. The first group (\w) is $1 the second (\w\w) $2 etc…. You can have as many groups as you want.
The script above will extract one alphabetical character (\w) then will consider the next two ones (\w\w) then the next 2 numerical character (\d\d).
The print will output

  I am 33
You can also use that script
  $variable1 =” I am 33 years young, not 34 years old ”
  $variable1 =~ / (\D *)(\d*)/;
  print “$1 $2” ‘, “/n”;
  
\D*) will extract all the non numerical values until one numerical is found. In that case “I am” while (\d*) will extract the numerical values coming after the one previously extracted. In that case “33”.
Another method can be used to look more discriminatively.
  @array1 = (“me”,”be”,”te”,”ce”);
  foreach (@array1) {
  If (/[mbc]e/) {
  print “$_”;
  } 
  }
  
This script will look for each elements of the array. If it contains any of the letters [mbc] preceding the letter ”e” the element of the array will be printed.
In that case “te” would not match while “me” , “be”, “ce” would.
You can also be more specific.
  @array1 = (“me”,”be”,”te”,”ce”);
  foreach (@array1) {
  If (/me|ce|te|/) {
  print “$_”;
  } 
  }
  
Me , ce, te would match. Notice that the order does not matter. In that case
  @array1 = (“me”,”be”,”te”,”ce”);
  foreach (@array1) {
  If (/me|te|ce|/) {
  print “$_”;
  } 
  }
  
Would have the same effect.