Jonathan
Jonathan

Reputation: 2738

Understanding re.search in Python

I am trying to allow users to Enter alphanumerics,underscores and spaces for a name. I've been using if not re.search(r'^[\w-]+$', name): to check if the name has anything other than alphanumerics,underscores and spaces. But here I can just enter one word, not multiple. What am I doing wrong?

Upvotes: 1

Views: 4322

Answers (3)

jdotjdot
jdotjdot

Reputation: 17072

You're not doing anything obviously wrong. Your question isn't totally clear either, so I'll try to address a couple of the possible issues.

Why is only one word accepted by the regex?

In your regex, you have \w, which according to the re documentation, is just alphanumeric characters and underscore. What you have not included is the space character, so any name with a space (including if it's separating first and last name) will be matched by your regular expression, and therefore turned to False by the not. What you should do to check if there are any non-alphanumeric characters/underscores/spaces is the following:

if not re.search(r'^[\w- ]+$', name):

Or, if you also for some reason are concerned about newlines (\n) or tabs (\t) and other kinds of whitespace:

if not re.search(r'^[\w\s- ]+$', name):

Why can I only check one name at a time?

That's because the regex will only search one string at a time. If you want to have it check multiple names, you should run the regular expression against each name, in a format like this:

# assuming name_list is a list of name strings
for name in name_list:
    if not re.search(r'^[\w- ]+$', name):
        # do whatever

Upvotes: 6

aemdy
aemdy

Reputation: 3802

You need to learn a little bit about regular expressions.

I personally started from Google classes and it was good enough to read the docs.

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

Your regex doesn't allow spaces (instead it allows dashes which you didn't mention in your question).

if not re.search(r'^[\w ]+$', name):

only allows ASCII letters, digits, underscore and spaces (and requires at least one character).

Upvotes: 2

Related Questions