Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- how do I use re to match a whole string [duplicate]

I am validating the text input by a user so that it will only accept letters but not numbers. so far my code works fine when I type in a number (e.g. 56), it warns me that I should only type letters and when I type in letters it doesn't return anything (like it should do). My problem is that it accepts it when I start by typing letters followed by numbers e.g. (s45). what it does is accept the first letter but not the whole string. I need it to accept the whole string.

def letterCheck(aString):     if len(aString) > 0:         if re.match("[a-zA-Z]", aString) != None:             return ""     return "Enter letters only" 
like image 722
Thomas Avatar asked Apr 11 '13 17:04

Thomas


People also ask

How do you match a whole word in Python?

\w -- (lowercase w) matches a "word" character: a letter or digit or underbar [a-zA-Z0-9_]. Note that although "word" is the mnemonic for this, it only matches a single word char, not a whole word. \W (upper case W) matches any non-word character. \b -- boundary between word and non-word.

How do you rematch in Python?

match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.

Does re match return a string?

Both return the first match of a substring found in the string, but re. match() searches only from the beginning of the string and return match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none.


1 Answers

Anchor it to the start and end, and match one or more characters:

if re.match("^[a-zA-Z]+$", aString): 

Here ^ anchors to the start of the string, $ to the end, and + makes sure you match 1 or more characters.

You'd be better off just using str.isalpha() instead though. No need to reach for the hefty regular expression hammer here:

>>> 'foobar'.isalpha() True >>> 'foobar42'.isalpha() False >>> ''.isalpha() False 
like image 132
Martijn Pieters Avatar answered Sep 17 '22 17:09

Martijn Pieters