2010-03-30 93 views

Trả lời

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

nên làm tốt. Theo như tôi biết không có bất kỳ phương pháp tích hợp nào.

+0

Lưu ý rằng điều này không hoạt động với các ký hiệu unicode, ví dụ: ''éllo'' – Almar

1

Trong Python < 3.0 điều này khá dễ dàng, vì bạn không thể có các ký tự unicode trong số nhận dạng. Điều đó sẽ làm việc:

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_] 'cho char đầu tiên. – bobince

+0

Tốt, nhưng số nhận dạng có thể bắt đầu bằng dấu gạch dưới. –

+0

Vâng, tôi đã nghĩ về điều đó khi tôi viết bài này. –

12

module tokenize định nghĩa một regexp gọi Tên

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

Đối với các mục đích này, bạn cần '^' + tokenize.Name + '$'. –

+0

Thêm vào kiểm tra các từ dành riêng cho python và tôi thích điều này. –

+2

@Douglas S.J. De Couto - bạn có thể sử dụng 'import keyword',' keyword.iskeyword (astring) 'để kiểm tra xem chuỗi có phải là từ khóa hay không, xem tài liệu của nó [here] (http://docs.python.org/library/keyword.html # keyword.iskeyword). – Abbafei

1

câu trả lời tốt cho đến nay. Tôi sẽ viết nó như thế này

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

Cần cho phép viết hoa. Các câu trả lời ở trên có vấn đề tương tự. –

+0

@Douglas: đó là cờ 're.I' dành cho. – SilentGhost

0

Những gì tôi đang sử dụng:

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

're.match' khớp từ đầu dòng. – SilentGhost

1

Tôi đã quyết định đi vết nứt khác tại này, vì đã có một vài gợi ý tốt. Tôi sẽ cố gắng củng cố chúng. Sau đây có thể được lưu dưới dạng mô-đun Python và chạy trực tiếp từ dòng lệnh. Nếu chạy, nó sẽ kiểm tra hàm, do đó, có thể là đúng (ít nhất là trong phạm vi tài liệu chứng minh khả năng).

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

Tất cả các giải pháp đề xuất cho đến nay không hỗ trợ Unicode hoặc cho phép một số trong các char đầu tiên nếu chạy trên Python 3.

Chỉnh sửa: các giải pháp được đề xuất chỉ nên được sử dụng trên Python 2 và trên Python3 isidentifier nên được sử dụng. Đây là một giải pháp mà nên làm việc ở bất cứ đâu:

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

Về cơ bản, nó kiểm tra xem một cái gì đó bao gồm (ít nhất là 1) nhân vật (bao gồm cả số), và sau đó nó sẽ kiểm tra rằng char đầu tiên không phải là số.

Các vấn đề liên quan