Reputation: 3
I am learning Python input validation with the re
library.
Currently I am using the following:
valid = re.match('[1-5]', UserInput)
I wish to make sure the input is between 1
and 5
.
There is just one problem with this method; if I input something that begins with 1-5
followed by something else (for example, 1bdfgh, 354), it is considered valid.
Is there a way around this? I would prefer the solution still using the re
library as it is for school.
Upvotes: 0
Views: 257
Reputation:
re.match
will only check if the string starts with the pattern you give it. To have it match the whole string, you can do:
valid = re.match('[1-5]$', UserInput)
In a Regex pattern, $
represents the end of the string. So, the above pattern will match strings that start with a character in the set [1-5]
and then end. The only strings which satisfy this condition are '1'
, '2'
, '3'
, '4'
, and '5'
.
Note that in Python 3.4, you can use re.fullmatch
for this:
valid = re.fullmatch('[1-5]', UserInput)
It is the same as re.match
, except that it matches the whole string rather than just the start.
Upvotes: 1
Reputation: 52151
You can use word boundaries
>>> a = '1sdv'
>>> valid = re.match('[1-5]',a)
>>> valid.group() # Wrong Match
'1'
>>> valid = re.search(r'^\b[1-5]\b$',a) # Correct Way
>>> valid.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> a = '1'
>>> valid = re.search(r'^\b[1-5]\b$',a)
>>> valid.group()
'1'
>>> a = '1 potato'
>>> valid = re.search(r'^\b[1-5]\b$',a)
>>> valid.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
Upvotes: 2
Reputation: 5156
You can use ^
(beginning of input) and $
(end of input) tokens, transforming your regex into:
^[1-5]$
But for numerical range checking, there's a much simpler solution:
theNumber = int(UseInput)
valid = 1 <= theNumber <= 5
Or even:
theNumber = int(UserInput)
valid = theNumber in range(1,6) #up to six, exclusive, so from 1 to 5 inclusive
Upvotes: 1
Reputation: 4035
re.match
only checks beginning of the string. You could use;
valid = re.search('[1-5]',UserInput)
Which is checking all over the string.
Upvotes: 0