#!/lusr/bin/perl use warnings; use strict; #------------------------------------------------------------------ #variable =~ m/regular_expression/ #------------------------------------------------------------------ my $str = "My phone number is 123-4567. This is my home phone."; if( $str =~ /\d{3}-\d{4}/ ){ print "There is a phone number in the string:\n\t'$str'\n"; }else{ print "There is not a phone number in the string:\n\t'$str'\n"; } #------------------------------------------------------------------ #$& - contains the matching substring #$` - contains the substring on the left of the match #$' - contains the substring on the right of the match #------------------------------------------------------------------ $str = "My phone number is 123-4567. This is my home phone."; if( $str =~ /\d{3}-\d{4}/ ){ print "There is a phone number in the string:\n\t'$str'\n"; print "The phone is: $&\n"; print " Before: '$`'\n"; print " After: '$''\n"; }else{ print "There is not a phone number in the string:\n\t'$str'\n"; } #----------------------------------------------------------------- $str = "My phones: 123-4567 (home), 234-5678 (office), 345-6789 (cell)."; while( $str =~ /\d{3}-\d{4}/ ){ print "The phone is: $&\n"; $str = $'; } #----------------------------------------------------------------- $str = "My phones: 123-4567 (home), 234-5678 (office), 345-6789 (cell)."; my @phones = $str =~ /\d{3}-\d{4}/g; foreach my $phone (@phones){ print "$phone\n"; } #----------------------------------------------------------------- #Getting information about a match #----------------------------------------------------------------- my $today = "10/16/2006"; #my $today = "10-16-2006"; if( $today =~ /\b(1[0-2]|0?[1-9])[\-\/](0?[1-9]|[12][0-9]|3[01])[\-\/]((19|20)\d{2})/ ){ print "Date: $&\n"; print "Month: $1\n"; print "Day: $2\n"; print "Year: $3\n"; print "Century: ", $4 + 1, "\n"; } #----------------------------------------------------------------- #String replacement #----------------------------------------------------------------- my $card = "1234 56789012-3456"; if( $card =~ /(\d\d\d\d)[\-\s]?(\d\d\d\d)[\-\s]?(\d\d\d\d)[\-\s]?(\d\d\d\d)/ ){ $card = "$1-$2-$3-$4"; }else{ $card = "Invalid credit card number!"; } print "$card\n"; #----------------------------------------------------------------- $card = "1234 56789012-3456"; if( $card =~ s/\d{4}/****/ ){ print "$card\n"; }else{ print "Sorry, there is no match\n"; } #----------------------------------------------------------------- $card = "1234 56789012-3456"; $card =~ s/(\d\d\d\d)[\-\s]?/$1-/g; # separate 4-digit groups with dashes $card =~ s/-$//; # remove the trailing dash $card =~ s/\d{4}-/****-/g; # substitute 4-digit groups with 4 stars print "$card\n";