Python 正则表达式,就好像字符串是变量一样

Python 正则表达式,就好像字符串是变量一样,python,regex,Python,Regex,我正在使用一个脚本来确定我的字符串是否为有效变量。 这是非常基本的,但我似乎不知道如何使用正则表达式 所以基本上我想要: A-Z a-z 0-9 no whitespace anywhere no special char except _ 可能吗? 这就是我所尝试的: re.match("[a-zA-Z0-9_,/S]*$", char_s): 单词\w字符类相当于[a-zA-Z0-9]。标识符不能以数字开头,因此第一个字符匹配[^\W\d],其余字符匹配\W*。这样的模式应该可以: ^[

我正在使用一个脚本来确定我的字符串是否为有效变量。 这是非常基本的,但我似乎不知道如何使用正则表达式

所以基本上我想要:

A-Z
a-z
0-9
no whitespace anywhere
no special char except _
可能吗? 这就是我所尝试的:

re.match("[a-zA-Z0-9_,/S]*$", char_s):

单词\w字符类相当于[a-zA-Z0-9]。标识符不能以数字开头,因此第一个字符匹配[^\W\d],其余字符匹配\W*。

这样的模式应该可以:

^[a-zA-Z_][a-zA-Z0-9_]*$
或者更简单地说:

^(?!\d)\w+$
在这两种情况下,只要不以数字开头,它将匹配由一个或多个字母、数字或下划线组成的字符串


那个?!…在第二种模式中,是一个否定的前瞻性断言。它确保第一个字符不是数字。更多信息可在.

中找到,在提到的正则表达式之上,您需要确保它不是下列之一:

比如说:

reserved = ["and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try"]

def is_valid(keyword):
    return (keyword not in reserved and
            re.match(r"^(?!\d)\w+$", keyword) # from p.s.w.g answer
或者像@nofinator建议的那样,你可以也应该直接使用。

正确的方法:

Python 2

Python 3

请注意,Python2的方法在Python3上以静默方式失败


当您看到这类问题时,首先要问的是Python是如何做到的?因为它几乎总是向用户公开一个方法。

您也可以使用keyword.iskeyword。看@nofinator Nice,我不知道。是的,这是我用的关键字。你需要在前面用“^”来锚定你的模式,所以字母no number出现在开头。。。
and       del       from      not       while    
as        elif      global    or        with     
assert    else      if        pass      yield    
break     except    import    print              
class     exec      in        raise              
continue  finally   is        return             
def       for       lambda    try
reserved = ["and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try"]

def is_valid(keyword):
    return (keyword not in reserved and
            re.match(r"^(?!\d)\w+$", keyword) # from p.s.w.g answer
import re
import keyword
import tokenize

re.match(tokenize.Name+"$", char_s) and not keyword.iskeyword(char_s)
import keyword

char_s.isidentifier() and not keyword.iskeyword(char_s)