问题描述
我正在验证用户输入的文本,以使其仅接受字母,而不接受数字.到目前为止,当我输入数字时(例如56),我的代码可以正常工作,它警告我只能输入字母,而当我输入字母时,它不返回任何内容(就像它应该那样).我的问题是,当我开始输入字母后跟数字时,它会接受它. (s45).它的作用是接受第一个字母,但不接受整个字符串.我需要它来接受整个字符串.
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"
推荐答案
将其固定到开头和结尾,并匹配一个或多个字符:
Anchor it to the start and end, and match one or more characters:
if re.match("^[a-zA-Z]+$", aString):
在这里^
锚定到字符串的开头,$
锚定到字符串的末尾,并且+
确保您匹配1个或多个字符.
Here ^
anchors to the start of the string, $
to the end, and +
makes sure you match 1 or more characters.
最好使用 str.isalpha()
更好.无需在这里拿起沉重的正则表达式锤子:
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
这篇关于Python-如何使用re匹配整个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!