Regex and Input validation in python
Question:
I’m trying to validate an input with regex to make sure the input is something like: 0,7
0 being the lowest number
7 being the highest number
they need to be separated with and “,”
I’ve tried using
re.match("[0-7,0-7]", input):
No luck
Answers:
You need to do:
re.match("[0-7],[0-7]$", input):
In Regex, [...]
is a character set. This means that, in your original pattern, you were looking for a single character that is either a comma or a digit in the range of 0 to 7. Adding 0-7
twice does nothing.
Also, I don’t know what input
is, but if it is a variable, then you should change its name. Having a variable named input
overshadows the built-in.
If input
is the built-in though, then you need to invoke it by adding ()
at the end:
re.match("[0-7],[0-7]$", input()):
import http.cookiejar
class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
def set_ok(self, cookie, request):
if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
return False
if i_dont_want_to_store_this_cookie(cookie):
return False
return True
Rx .|. Racoon =< c
I’m trying to validate an input with regex to make sure the input is something like: 0,7
0 being the lowest number
7 being the highest number
they need to be separated with and “,”
I’ve tried using
re.match("[0-7,0-7]", input):
No luck
You need to do:
re.match("[0-7],[0-7]$", input):
In Regex, [...]
is a character set. This means that, in your original pattern, you were looking for a single character that is either a comma or a digit in the range of 0 to 7. Adding 0-7
twice does nothing.
Also, I don’t know what input
is, but if it is a variable, then you should change its name. Having a variable named input
overshadows the built-in.
If input
is the built-in though, then you need to invoke it by adding ()
at the end:
re.match("[0-7],[0-7]$", input()):
import http.cookiejar
class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
def set_ok(self, cookie, request):
if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
return False
if i_dont_want_to_store_this_cookie(cookie):
return False
return True
Rx .|. Racoon =< c