should do the trick. The ^ and $ "anchor" the regex to the beginning and end of the string, so that matches the beginning of the string, followed by one or more digits, followed by '.txt', followed by the end of the string. If you define 1.1.txt as being OK (and the way I read it, 1.1 is a number), then:/^\d+\.txt$/
will work. (...)? matches zero or one instances of whatever's inside the brackets, making the decimal point and any digits after it optional. And finally, to optionally allow negative numbers:/^\d+(\.\d+)?\.txt$/
The brackets in those last two, which I'm really just using for grouping, will have the side-effect of capturing their contents into the $1 variable. You can avoid that by inserting more line-noise into the pattern, which I left out here in the interests of clarity. Search for the word 'clustering' in the perlre manpage for details./^-?\d+(\.\d+)?\.txt$/
A completely different approach would be to use perl's automatic conversion between strings and numbers. If you evaluate a scalar that begins with a number in a numberish way - eg by adding it to 0 - the result is the number at the beginning of the string. For instance:
or if you only want integers ...print 0+"1.1.1.txt" # 1.1 print 0+"-3.14.foo" # -3.14
Adapting your code to use this method - and to round your numbers properly - is left as an exercise for the reader :-)print int("1.1.1.txt") # 1 print int("-3.14.foo") # -3
In reply to Re: regex matching number
by DrHyde
in thread regex matching number
by InfiniteSilence
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |