Consequetive pattern match in Perl
Make a pattern that will match three consecutive copies of whatever is currently contained in $what. That is, if$what="fred" , your pattern should match "fredfredfred".
If
$what is "fred|barney", your pattern should match
"fredfredbarney" and
"barneyfredfred" and
"barneybarneybarney" and many other variations.
Well, This is quite tricky. But the magic match to do over here is :
/($str){3}/
Below is the example code:
#!/usr/bin/perl use warnings; use strict; # notice the example has the `|`. Meaning # match "fred" or "barney" 3 times. my $str = 'fred|barney'; my @tests = qw(fred fredfredfred barney barneybarneybarny barneyfredbarney); for my $test (@tests) { if( $test =~ /^($str){3}$/ ) { print "$test matched!\n"; } else { print "$test did not match!\n"; } }
Below is the execution:
> ./temp9.pl fred did not match! fredfredfred matched! barney did not match! barneybarneybarny did not match! barneyfredbarney matched!
0 comments: