Python-如何使用 re 匹配整个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15954650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:26:24  来源:igfitidea点击:

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

pythonstringmatch

提问by Thomas

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.

我正在验证用户输入的文本,以便它只接受字母而不接受数字。到目前为止,当我输入一个数字(例如 56)时,我的代码工作正常,它警告我应该只输入字母,而当我输入字母时,它不会返回任何内容(就像它应该做的那样)。我的问题是当我开始输入字母后跟数字时它会接受它,例如(s45)。它的作用是接受第一个字母而不是整个字符串。我需要它来接受整个字符串。

def letterCheck(aString):
    if len(aString) > 0:
        if re.match("[a-zA-Z]", aString) != None:
            return ""
    return "Enter letters only"

采纳答案by Martijn Pieters

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

将其锚定到开头和结尾,并匹配一个或多个字符:

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.

此处^锚定到字符串的开头和$结尾,并+确保匹配 1 个或多个字符。

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

不过,您最好只使用str.isalpha()它。无需在这里使用庞大的正则表达式锤子:

>>> 'foobar'.isalpha()
True
>>> 'foobar42'.isalpha()
False
>>> ''.isalpha()
False

回答by Aprillion

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

在正则表达式 + 原始字符串中使用边界对正则表达式进行编码,如下所示:

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

回答by sizzzzlerz

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

您可以考虑在字符串上使用 isalpha() 。如果字符串只包含字母字符,则返回 true,否则返回 false。

if aString.isalpha():
   do something
else:
   handle input error

回答by Louis

if you look for pretty pythonic writings, go for isalpha and isdecimal :

如果您寻找漂亮的 Pythonic 作品,请选择 isalpha 和 isdecimal :

str = u"23443434";
print str.isdecimal();