3

This is my attempt

def matcher(ex):
    if re.match(r'^[\w|\d][A-Za-z0-9_-]+$', ex):
        print 'yes'

My goal is to match only submission that satisfy all the followings

  1. begins with only a letter or a numeric digit, and
  2. only letter, space, dash, underscore and numeric digit are allowed
  3. all ending spaces are stripped

In my regex, matcher('__') is considered valid. How can I modify to achieve what I want really want? I believe \w also includes underscore. But matcher('_') is not matched...

4

1 回答 1

12
def matcher(ex):
    ex = ex.rstrip()
    if re.match(r'^[a-zA-Z0-9][ A-Za-z0-9_-]*$', ex):
        print 'yes'

原始正则表达式中的问题:

  1. |并不意味着字符类中的交替,而是字面上的管道字符。

  2. 您用于+以下字符,表示一个或多个,因此一个字符的字符串'_'不匹配。

  3. \w在你的第一个字符中使用了,它接受下划线。

于 2012-07-16T01:49:09.540 回答