The reason you're getting a match is that the number '1' is there, it's sitting right at the start of your string- closely followed by another '1' which the regular expression doesn't care about. It just sees that first '1' and stops, not bothering to look ahead.

If you really do need to throw regexps at this (For example the number is embedded in the string 'I have 10 hamsters') then you need to look at restricting it.

The following regular expression matches the following.. either start of line or something that isn't a digit, followed by the number you're after, finally followed either by something else that isn't a digit or the end of the line. It will also store the number it found in $1 (Note the use of (?: ... ) to allow me to use non-capturing brackets).

#!/usr/bin/perl -w use strict; my @tests = ( 'I have 4 hamsters', '10', '11', 'I have 23 camels', 'Where is my wallaby?', '0', '1 1', ); foreach my $test (@tests) { if ($test =~ /(?:\D|^)([1-9]|10)(?:\D|$)/) { print "'$test' matches with the number $1\n"; } else { print "'$test' does not match\n"; } }

The moral of this story: Regexp's will do exactly what you tell them to do, not what you want them to do. Be careful to check you're capturing in the correct context. I'd recommend the O'Reilly book 'Mastering Regular Expressions' if you're going to be doing a lot of this stuff.


In reply to Re: regular expression to match numbers by Molt
in thread regular expression to match numbers by Vanesa

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.