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

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


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


use boundaries in your regex + raw string to encode the regex, like this:

r"^[a-zA-Z]+$"


You might consider using isalpha() on the string. It returns true if the string contains nothing but alphabetic characters, false otherwise.

if aString.isalpha():   do somethingelse:   handle input error