SPUG: regarding Perl doubt

Paul Goracke paul at goracke.org
Sun Jan 25 09:58:52 PST 2009


On Jan 25, 2009, at 12:29 AM, battipatisainagendra Bhavaniprasad wrote:

> Hi,
>        I am new to this community.I have question regarding Pattern  
> Matching in Perl.

Welcome!

> 1.when /ab?/ is given it returns true for "abbbb" but my question is  
> "?" will support zero or one occurrence.

It does, and it did. Match regexes only tell you whether the pattern  
exists in the string. To find out what the expression actually  
matched, use capture parentheses: "/(ab?)/" will show that you matched  
"ab" (in $1 after the match). If you want to _not_ match your example  
string, you'd need something like /ab?[^b]/

But that will match "abcdefg" as well. If that _still_ isn't what you  
want, you may need to look at the "\b" word boundaries, or ^ and $ if  
you're only trying to match an entire string. Welcome to the joys of  
pattern matching, where it's at least as important what you _don't_  
match as what you do.

> 2.When i am giving /[0-9a-zA-Z] it returns true for "0AA" and "9aa"  
> but my question is IT HAS TO ACCEPT ONLLY "0aa"/"9fG"....so on.

Break it down to one position at a time: /[0-9][a-z][A-Z]/

And think about what you don't want to match, a la question one.

> 3.What is the difference between Pattern Matching and regular  
> expression?Are both same?

Ah, semantics fun time.

Pattern matching is the action of matching a desired pattern; regular  
expressions are just a way of expressing the desired pattern(s) to  
match. Pattern matching could be applied to colors or shapes, but you  
would probably need to find a different way of expressing the desired  
match than regex.

pg




More information about the spug-list mailing list