Python - how to use re to match an entire string

I check the text input by the user so that he accepts letters, not numbers. while my code works fine, when I type in a number (for example, 56), it warns me that I should write only letters, and when I type letters, it returns nothing (as it should be done). My problem is that it takes it when I start by entering letters followed by numbers, for example. (S45). what he does is accept the first letter, but not the entire 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" 
+14
python string match
source share
5 answers

Bind it to the beginning and end and match one or more characters:

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

Here ^ attached to the beginning of the line, $ to the end, and + guarantees the matching of 1 or more characters.

It is best to use str.isalpha() . No need to get to the healthy regular hammer expression here:

 >>> 'foobar'.isalpha() True >>> 'foobar42'.isalpha() False >>> ''.isalpha() False 
+38
source share

use your regex + raw line borders to encode the regular expression, for example:

 r"^[a-zA-Z]+$" 
+4
source share

You can use isalpha () in a string. It returns true if the string contains only alphabetic characters, otherwise false.

 if aString.isalpha(): do something else: handle input error 
+3
source share

if you are looking for beautiful pythonic works, go to isalpha and isdecimal:

 str = u"23443434"; print str.isdecimal(); 
0
source share

Million dollar question. My post was rejected due to this post. But there seems to be insufficient information for a successful conclusion.

I need to use a regular expression to find ANY exactly five characters, including line feed. I have this so far:

  five = "s6<\na" m = re.match(r"^.{5}$+",six,re.DOTALL) 

This is the error I get:

  File "q01d.py", line 10, in <module> m = re.match(r"^.{5}$+",five,re.DOTALL) sre_constants.error: nothing to repeat 

I’m not sure what we are not doing here, but I’ll publish it if I decide this in between.

0
source share

All Articles