views:

220

answers:

4

Hi,

I looked and searched and couldn't find what I needed although I think it should be simple (if you have any Python experience, which I don't).

Given a string, I want to verify, in Python, that it contains ONLY alphanumeric characters: a-zA-Z0-9 and . _ -

examples:

Accepted:

bill-gates

Steve_Jobs

Micro.soft

Rejected:

Bill gates -- no spaces allowed

[email protected] -- @ is not alphanumeric

I'm trying to use:

if re.match("^[a-zA-Z0-9_.-]+$", username) == True:

But that doesn't seem to do the job...

+4  A: 

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(...).

Mark Rushakoff
+2  A: 

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):
Ignacio Vazquez-Abrams
+1  A: 

Could also shorten it slightly to :

if re.match(r'^[\w.-]+$', username):
Brendan Abel
A: 

If you are going to use it for many comparisons is wise to compile it

import re 
ALPHANUM=re.compile('^[a-zA-Z0-9_.-]+$')

for u in users:
    if ALPHANUM.match(u) is None:
        print "invalid"
fabrizioM