Perl Programming/Regular Expressions

From Wikibooks, open books for an open world
< Perl Programming
Jump to: navigation, search
Previous: References and Data Structures Index Next: Regular Expression Operators

Regular expressions are tools for complex searching of text, considered one of the most powerful aspects of the Perl language. A regular expression can be as simple as just the text you want to find, or it can include wildcards, logic, and even sub-programs.

To use regular expressions in perl, use the =~ operator to bind a variable containing your text to the regular expression:

  $Haystack =~ /needle/;

This returns 1 if "needle" is contained within $HayStack, or 0 otherwise.

  $Haystack =~ /needle/i;    # The i means "case-insensitive"

  $Haystack =~ /(needle|pin)/;  # Either/Or statements

  $Haystack =~ /needle \d/;     # "needle 0" to "needle 9"

Regular expression can also be used to modify strings. You can search and replace complex patterns by using the regex format s///

  $msg = "perl is ok";
  $msg =~ s/ok/awesome/;           # search for the word "ok" and replace it with "awesome"

($msg is now "perl is awesome")


Previous: References and Data Structures Index Next: Regular Expression Operators