Dual-license your content for inclusion in The Perl 5 Wiki using this HOWTO, or join us for a chat on irc.freenode.net#PerlNet.

Beginners/What are Regular Expressions all about

From PerlNet

Jump to: navigation, search

Perl 5 Regular Expressions are a way to search a text for an occuring pattern. A pattern can be a substring or something more complex. Here's a simple example:


   $string = "I don't believe in fairies. " .
       "Oops! A fairy died. " . 
       "I don't believe in fairies. " . 
       "Oops! Another fairy died";
   
   if ($string =~ m/fairy/)
   {
       print "The string contains the word 'fairy'";
   }

Now, the regular expression comes inside a m/ ... /, and it operates on the string using =~. In our case, the expression is a substring "fairy", but it can be more complex. For instance m/f[ai]*ry/ will match 'f', followed by zero or more occurrences of the letters 'a' or 'i', followed by "ry".

Perl allows you to do several things using regular expressions: find matches, extract sub-strings, and substitute matches with other expressions.

See Also

Personal tools