Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code to use a regular expression to make sure a string is alphanumeric plus . - _

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

like image 365
Warlax Avatar asked Mar 25 '10 21:03

Warlax


People also ask

How do you check if a string is alphanumeric in Python with regex?

For checking if a string consists only of alphanumerics using module regular expression or regex, we can call the re. match(regex, string) using the regex: "^[a-zA-Z0-9]+$". re. match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().

How do you represent alphanumeric in regular expression?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.

How do you check if a string is a regular expression in Python?

fullmatch(). This method checks if the whole string matches the regular expression pattern or not. If it does then it returns 1, otherwise a 0.


1 Answers

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

like image 179
Mark Rushakoff Avatar answered Oct 20 '22 03:10

Mark Rushakoff