Enigmatic
Enigmatic

Reputation: 4148

Why does my regex pattern allow digits?

I have tried creating a regex pattern that matches only letters and allows a whitespace:

import re
user_input = raw_input('Input: ')

if re.match('[A-Za-z ]', user_input):
    print user_input

However,

When inputting o888, or something similar, a match seems to still occur

Upvotes: 1

Views: 46

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

That happens because your regex allows partial matches.

Use

if re.match('[A-Za-z ]*$', user_input):
                      ^^

to anchor the pattern at the end and match 0+ chars. As re.match anchors the pattern at the start of the string, the ^ anchor is not necessary, but $ - end of string - is required to enforce the full string match.

If you do not want to allow an empty string, use + quantifier - one or more occurrences - rather than * (zero or more occurrences).

Upvotes: 5

Related Questions