2010-03-30 2 views

답변

2
re.match(r'[a-z_]\w*$', s, re.I) 

해야합니다. 내가 아는 한 기본 제공 방법이 없습니다.

+0

예 : 유니 코드 기호와 함께 작동하지 않습니다. ''éllo'' – Almar

1

파이썬 < 3.0에서는 식별자에 유니 코드 문자를 사용할 수 없으므로 매우 쉽습니다. 즉, 작업을 수행해야합니다

import re 
import keyword 

def isidentifier(s): 
    if s in keyword.kwlist: 
     return False 
    return re.match(r'^[a-z_][a-z0-9_]*$', s, re.I) is not None 
+0

'[a-z_]'첫 번째 문자. – bobince

+0

좋습니다. 그러나 식별자는 밑줄로 시작할 수 있습니다. –

+0

그래, 내가 이것을 쓰고있을 때 생각 중이 야. –

12

토큰 화 모듈 이름

지금까지
import re, tokenize, keyword 
re.match(tokenize.Name + '$', somestr) and not keyword.iskeyword(somestr) 
+3

이러한 목적으로 '^'+ 토큰 화. 이름 + '$'가 필요합니다. –

+0

python 예약어를 추가하십시오. 나는 이것을 좋아합니다. –

+2

@Douglas S.J. De Couto -'import keyword','keyword.iskeyword (astring)'을 사용하여 문자열이 키워드인지 확인 할 수 있습니다.이 문서의 [here] (http://docs.python.org/library/keyword.html)를 참조하십시오. # keyword.iskeyword). – Abbafei

1

좋은 답변이라고하는 정규 표현식을 정의합니다. 나는 이것을 이렇게 쓰고 싶다. 몇 가지 좋은 제안이 있었다 때문에 나는이 또 다른 균열을하기로 결정했습니다

def is_valid_keyword_arg(k): 
    """ 
    Return True if the string k can be used as the name of a valid 
    Python keyword argument, otherwise return False. 
    """ 
    # Don't allow python reserved words as arg names 
    if k in keyword.kwlist: 
     return False 
    return re.match('^' + tokenize.Name + '$', k) is not None 
+0

대문자 허용 필요. 위의 답변도 비슷한 문제가 있습니다. –

+0

@Douglas : 그것은're.I' 플래그가있는 것입니다. – SilentGhost

0

. 나는 그들을 통합하려고 노력할 것이다. 다음은 Python 모듈로 저장하고 명령 행에서 직접 실행할 수 있습니다. 실행되면 함수를 테스트하므로 정확하게 정확합니다 (적어도 문서에서 기능을 보여주는 정도까지).

import keyword 
import re 
import tokenize 

def isidentifier(candidate): 
    """ 
    Is the candidate string an identifier in Python 2.x 
    Return true if candidate is an identifier. 
    Return false if candidate is a string, but not an identifier. 
    Raises TypeError when candidate is not a string. 

    >>> isidentifier('foo') 
    True 

    >>> isidentifier('print') 
    False 

    >>> isidentifier('Print') 
    True 

    >>> isidentifier(u'Unicode_type_ok') 
    True 

    # unicode symbols are not allowed, though. 
    >>> isidentifier(u'Unicode_content_\u00a9') 
    False 

    >>> isidentifier('not') 
    False 

    >>> isidentifier('re') 
    True 

    >>> isidentifier(object) 
    Traceback (most recent call last): 
    ... 
    TypeError: expected string or buffer 
    """ 
    # test if candidate is a keyword 
    is_not_keyword = candidate not in keyword.kwlist 
    # create a pattern based on tokenize.Name 
    pattern_text = '^{tokenize.Name}$'.format(**globals()) 
    # compile the pattern 
    pattern = re.compile(pattern_text) 
    # test whether the pattern matches 
    matches_pattern = bool(pattern.match(candidate)) 
    # return true only if the candidate is not a keyword and the pattern matches 
    return is_not_keyword and matches_pattern 

def test(): 
    import unittest 
    import doctest 
    suite = unittest.TestSuite() 
    suite.addTest(doctest.DocTestSuite()) 
    runner = unittest.TextTestRunner() 
    runner.run(suite) 

if __name__ == '__main__': 
    test() 
+0

're.match'는 줄의 처음부터 일치합니다. – SilentGhost

1

: 내가 사용하고 무엇

import keyword 
import re 

def isidentifier(candidate): 
    "Is the candidate string an identifier in Python 2.x" 
    is_not_keyword = candidate not in keyword.kwlist 
    pattern = re.compile(r'^[a-z_][a-z0-9_]*$', re.I) 
    matches_pattern = bool(pattern.match(candidate)) 
    return is_not_keyword and matches_pattern 
0

모든 솔루션은 유니 코드를 지원하거나 파이썬 3에 실행하면 첫 번째 문자 에 숫자를 허용하지 않습니다 지금까지 제안했다.

편집 : 제안 된 솔루션은 Python 2에서만 사용해야하며 Python3에서는 isidentifier을 사용해야합니다.

re.match(r'^\w+$', name, re.UNICODE) and not name[0].isdigit() 

기본적으로, 그것은 뭔가 (번호 포함) (최소 1) 문자로 구성 여부를 테스트 한 다음 첫 번째 문자가 숫자가 아닌 것을 확인 : 여기 어디서든 작동합니다 솔루션입니다.

관련 문제