Python code to use a regular expression to make sure a string is alphanumeric plus . - _
re.match
does not return a boolean; it returns a MatchObject
on a match, or None
on a non-match.
>>> re.match("^[a-zA-Z0-9_.-]+$", "hello")
<_sre.SRE_Match object at 0xb7600250>
>>> re.match("^[a-zA-Z0-9_.-]+$", " ")
>>> print re.match("^[a-zA-Z0-9_.-]+$", " ")
None
So, you shouldn't do re.match(...) == True
; rather, you should be checking re.match(...) is not None
in this case, which can be further shortened to just if re.match(...)
.
Never use == True
or == False
in a comparison. Many types already have a bool equivalent which you should use instead:
if re.match("^[a-zA-Z0-9_.-]+$", username):
Could also shorten it slightly to :
if re.match(r'^[\w.-]+$', username):