Perl Tutorials -Part 59- Using quantifiers: 1

Posted on June 3, 2010. Filed under: Perl Tutorials |


#perl pattern matching example, quantifiers

$_ = 'My favourite mumbers are 13, 5, 7 and 9.';
#[^ ] means any character except space, + means match one or more times
@words = /[^ ]+/g;
foreach (@words)
{
    print "$_\n";
}

print "\n\n";
#[a-z] means only alphabetic character
@words = /[a-z]+/gi;
foreach (@words)
{
    print "$_\n";
}

print "\n\n";
# get all numbers
@words = /[0-9]+/gi;
foreach (@words)
{
    print "$_\n";
}

print "\n\n";
#all individual numbers
@words = /[^0-9][0-9]/gi;
foreach (@words)
{
    print "$_\n";
}

print "\n\n";
#all 2 digit numbers
@words = /[^0-9][0-9]{2}/gi;
foreach (@words)
{
    print "$_\n";
}

Output:

My
favourite
mumbers
are
13,
5,
7
and
9.

My
favourite
mumbers
are
and

13
5
7
9

 1
 5
 7
 9

 13
Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: