Perl Tutorials -Part 65- Examples of non-greedy matching

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


#perl exmale of greedy/non-greedy match
$_ = ‘300000000000000000000000000000000000000’;
#* means match 0 or more time
/30*/;
print $&;
print “\n”;

#? means match 1 or more time
/30*?/;
print $&;
print “\n”;

/30+?/;
print $&;
print “\n”;

#{2,5} means match 2 to 5 time
/30{2,5}?/;
print $&;
print “\n”;

/30{2,5}/;
print $&;
print “\n”;

$_ = ‘”What is the use of a book,” thought Alice, “without pictures”‘;
#[“‘] means ” or ‘
@quotes = /[“‘].*[“‘]/g;
foreach (@quotes)
{
print “$_\n”;
}
print “\n”;

@quotes = /[“‘].*?[“‘]/g;
foreach (@quotes)
{
print “$_\n”;
}

Output:

1
2
3
4
5
6
7
8
9
300000000000000000000000000000000000000
3
30
300
300000
"What is the use of a book," thought Alice, "without pictures"

"What is the use of a book,"
"without pictures"
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: