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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |