Defining re pattern for matching list of numbers

Chris Rebert clp2 at rebertia.com
Fri Nov 6 13:16:31 EST 2009


On Fri, Nov 6, 2009 at 8:04 AM, jorma kala <jjkk73 at gmail.com> wrote:
> Hi,
> I'm trying to write a re pattern to match a list of one or more numbers,
> each number is in the range of 1-15 value and the numbers are separated by
> spaces (but there are no spaces at the beginning and end of the string). For
> instance:
>
> "3"
> "1 14 8"
>
> but not:
>
> "22"
> " 5 11"
>
> I've come up with something like this
>
> re.compile("^((([1-9])|(1[0-8]))( +(?=[1-9]))*)+$")
>
> but I can't believe this has to be so complicated.

Your format seems so simple I have to ask why you're using regexes in
the first place.

try:
    nums = [int(num) for num in line.split(" ")]
except ValueError:
    print "Invalid input"

for num in nums:
    if num < 1 or num > 15:
        raise ValueError, "Number present which is outside of valid range"

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list