Home » Perl Basics » 10 - Regular Expressions
10

What are Regular Expressions

What are regular expressions?

Everything you put into // will be consider as regular expression. Regular expression are strings of character that perl will look for in the data it is processing. Regular expression need to be understood as it is the corner stone of Perl. Without them nothing can be done.

This is how to use regular expressions

  #!/usr/bin/perl 
  #author : you
  #date : 5.10.2007
  #purpose : regular expression
  $data1 = “Reg-express”;
  If ($data1 =~ /Reg-express/) {
  print “data1” , “\n”;
  }
  #END
  
Regular expressions use the operator “ =~ “ to do the matching. In the script above the string “Reg-express” will be matched against “Reg-express”.
The two match.
  ($data1  =~ /eg-express/)
#would also match because the string “eg-express” can be found in $data1.
  ($data1  =~ /reg-express/)
# would not match because the first character “r” does not match the first character of the $data1 “R”. Remember Perl is case sensitive.
Regular expressions is string matching. It doesn’t matter where in the string the match is done.
  ($data1  =~ /reg-express/i) 
#would match, the “ i “ in that case tells Perl to ignore the case.
Anchor Tags
Anchor tags are used to tell Perl where to look in the string.
  ($data1  =~ /^reg-express/i) 
# the “ ^ “ will tell Perl to look at the beginning of the string.
  ($data1  =~ /reg-express$/i) 
# The “ $ “ will tell Perl to look at the end of the string.
  ($data1  =~ /^reg-express$/i) 
# if we use the 2 tags Perl will try to find a match at both beginning AND end. If Perl doesn’t find a match at both beginning and end it will not return a match.

Example:

  #!/usr/bin/perl 
  #author : you
  #date : 5.10.2007
  #purpose : regular expression
  $data1 = “life is beautiful , it’s life”;
  If ($data1 =~ /^life/) { #MATCH
  print “data1” , “\n”;
  }
  If ($data1 =~ /life$/) { #MATCH
  print “data1” , “\n”;
  }
  If ($data1 =~ /^life$/) { #MATCH
  print “data1” , “\n”;
  }
  If ($data1 =~ /beatifull$/) { #DOES NOT MATCH
  print “data1” , “\n”;
  }
  #END