Python to use regex so the string is alphanumeric. - _

I searched and searched and could not find what I needed, although I think it should be simple (if you have Python experience that I don't know).

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

examples:

Accepted:

bill-gates

Steve_Jobs

Micro.soft

Rejected:

Bill gates - spaces are not allowed

me@host.com - @ is not alphanumeric

I am trying to use:

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

But that doesn't seem to work ...

+6
source share
6 answers

re.matchdoes not return boolean; it returns MatchObjectin coincidence or Nonein inconsistency.

>>> 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

, re.match(...) == True; , re.match(...) is not None , if re.match(...).

+17

== True == False . bool, :

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

:

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

:
1) 6-30
2) :

  • 0 9
  • _ -.

3) :

  • _ -.

  • _ -.

:
if re.match(r'^(?![-._])(?!.*[_.-]{2})[\w.-]{6,30}(?<![-._])$',username) is not None:

+1

, ( )

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

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

:

, re.match(), re.search() re.compile(), , , , .

0

utils:

def valid_re(self, s, r):
 reg = re.compile(r)
 return reg.match(s)

utils :

if not utils.valid_re(username, r'^[a-zA-Z0-9_.-]+$'):
        error = "Invalid username!"
0

All Articles