CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Problem with Regular Expression

 



Cupidvogel
Novice

Mar 30, 2012, 5:43 AM

Post #1 of 3 (786 views)
Problem with Regular Expression Can't Post

Hi, I am trying this code:


Code
$a = "12."; 
$a =~ /^\d*(\.\d{1,5})?/;
print $&;


Clearly the ? quantifier at the end of (\.\d{1,5}) ensures that for the pattern to match, a decimal point, if there, has to be followed by at least 1 digit, right? But on trying out with an input of 12.0, I am getting 12 as output. How come? The \d* matches 12 alright, but then because there is no digit following the decimal, shouldn't the match fail?


BillKSmith
Veteran

Mar 30, 2012, 7:26 AM

Post #2 of 3 (783 views)
Re: [Cupidvogel] Problem with Regular Expression [In reply to] Can't Post

Your question mark indicates that the whole expression within the parenthesis is optional. In your example, the pattern inside the parenthesis does not match anything, but it does not have to. The whole expression is considered a match.

You would get the behavior you expect if you put an end-of-string ($) anchor at the end of your regular expression. At the point that you require the end-of-string, you would still have the unmatched decimal point.

If you must match this pattern in the middle of a string, things become much more complicated. Refer to the documentation of positive look ahead under extended regular expressions.
Good Luck,
Bill


Cupidvogel
Novice

Mar 30, 2012, 7:33 AM

Post #3 of 3 (782 views)
Re: [BillKSmith] Problem with Regular Expression [In reply to] Can't Post

Right. Thanks.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives