Perl Quantifiers

Domain Hosting image
Web Hosting
Dedicated server
ssl certificate
Web Design image
Email

Sometimes, you may want to match an unknown number of repetitions of a string. For example, if you want to find" one or more hash characters, "you could use something like

if ("abd#def" =~ /#I##I###I####/) ...

But this isn't really general enough. Instead, you can use some other special characters outside the slashes to indicate how many copies of what's inside the slashes to match on. These counting characters are called quantifiers because they let you tell Perl the number of times that the string they follow can exist to be matched.

+ - Match 1 or more times
* - Match 0 or more times
? - Match 0 or 1 time
{n} - Match exacty n times
{n,} - Match at least n times
{n, m} - Match at least n but not more than m times (these values must be less than 65,536)

Thus, to search for "one or more hash characters, " you would use if($Test =- /#+/) ... To search for "exactly three digits," you would use if($Test =- ^d(3)/) ... You can combine quantifiers with character class to do some pretty neat things. For example, to search for a word that ends in a digit, you could use

if($Test =- ^w+\d/) ...

Remember how (earlier in the chapter) you saw this test :

if($Test =~/N.T/)
This code would match "NET" but would not match "NEST* (because NEST contains too many charcters). This code also would not match "NT" because NT has too few characters. If you want to match "N followed by one or more arbitary characters, followed by T", you would use

if($Test =~/N.+T/) ...

If you want to match "N followed by zero or more arbitrary characters, followed by T', you would instead use

if($Test =~/N.*T/) ...

To get the result of a test, you have to use grouping parentheses in the regular 'expression and then check Perl's special variables $1, $2, $3, and so on:

$Test="NESTING";
if($Test =~/(N*T)/)
( print "True\n"; ) else { print "false\n";)
print "$1\n";
When you run this program, Perl displays True
NEST

$1 matches the result of the first set of parentheses, $2 matches the result of the second set, and so on.



Domain Name Search

www.


Copyright (C) 2007. Web Domain design hosting. All rights reserved.