I need to parse input from the user so it has one of the following formats:
1321 .. 123123
or
-21323 , 1312321
A number (can be negative), a comma ,
or two dots ..
, and then another number (can be negative).
Also, the first number must be less or equal <=
to the second number.
If the input fails to have this format, ask again the user for input.
I have
def ask_range():
raw = raw_input()
raw = raw.strip(' \t\n\r')
raw = map((lambda x: x.split("..")), raw.split(","))
raw = list(item for wrd in raw for item in wrd)
if len(raw) != 2:
print "\nexpecting a range value, try again."
return ask_range()
I'm not sure how to get the numbers right.
EDIT
The solution I came up with the help from the answers is:
def ask_range():
raw = raw_input()
raw = raw.strip(' \t\n\r')
raw = re.split(r"\.\.|,", raw)
if len(raw) != 2:
print "\nexpecting a range value, try again."
return ask_range()
left = re.match(r'^\s*-?\s*\d+\s*$', raw[0])
right = re.match(r'^\s*-?\s*\d+\s*$', raw[1])
if not (left and right):
print "\nexpecting a range value, try again."
return ask_range()
left, right = int(left.group()), int(right.group())
if left > right:
print "\nexpecting a range value, try again."
return ask_range()
return left, right