Jump to content

Perl Programming/Regular expression operators

From Wikibooks, open books for an open world
Previous: Regular expressions Index Next: Regular expressions reference

Matching a string

[edit | edit source]
 # Shorthand form uses // to quote the regular expression
 $Text =~ /search words/;

 # The m function allows you to use your choice of quote marks
 $Text =~ m|search words|;
 $Text =~ m{search words};
 $Text =~ m<search words>;
 $Text =~ m#search words#;

Spliting a string into parts

[edit | edit source]
 # The split function allows you to split a string wherever a regular expression is matched
 @ArrayOfParts = split( /,/, $Text);     # Splits wherever a comma is found
 @ArrayOfParts = split( /\s+/, $Text);   # Splits where whitespace is found
 @ArrayOfParts = split( /,\s*/, $Text);  # Comma followed by optional whitespace
 @ArrayOfParts = split( /\n/, $Text);    # Newline marks where to split

Searching and replacing a string

[edit | edit source]
 # The s function allows you to search and replace within a string. s(ubstitute)
 $Text =~ s/search for/replace with/;
 $Text =~ s|search for|replace with|;
 $Text =~ s{search for}{replace with};

 # Putting a g (global) at the end, means it replaces all occurances and not just the first
 $Text =~ s/search for/replace with/g;

 # As with everything, putting an i (insensitive) at the end ignores the differences between
 # uppercase and lowercase.
 Use Locale;
 $Text =~ s/search for/replace with/i;

Extracting values from a string

[edit | edit source]
 # This function sets the variables $1, $2, $3 ... 
 #   to the information that it has extracted from a string.
 
 $Text =~ m/before(.*)after/;
 # So, if $Text was "beforeHelloafter", $1 is now "Hello"
   
 $Text =~ m/bef(.*)bet(.*)aft/;
 # This time, if $Text was "befOnebetTwoaft", $1 is now "One" and $2 is "Two"

 # It can also be used to extract certain kind of information.
 $Text =~ m|([^=]*)=(\d*)|;
   
 #If $Text was "id=889", $1 now equals "id" and $2 equals 889.
Previous: Regular expressions Index Next: Regular expressions reference