import re
smiley_pattern = '^(:\(|:\))+$' # matches only the smileys ":)" and ":("
def test_match(s):
print 'Value: %s; Result: %s' % (
s,
'Matches!' if re.match(smiley_pattern, s) else 'Doesn\'t match.'
)
should_match = [
':)', # Single smile
':(', # Single frown
':):)', # Two smiles
':(:(', # Two frowns
':):(', # Mix of a smile and a frown
]
should_not_match = [
'', # Empty string
':(foo', # Extraneous characters appended
'foo:(', # Extraneous characters prepended
':( :(', # Space between frowns
':( (', # Extraneous characters and space appended
':((' # Extraneous duplicate of final character appended
]
print('The following should all match:')
for x in should_match: test_match(x);
print('') # Newline for output clarity
print('The following should all not match:')
for x in should_not_match: test_match(x);
您原始代码的问题是您的正则表达式是错误的:(:\()
。让我们分解一下。
外部括号是“分组”。如果要进行字符串替换,它们就是您要引用的内容,并且可将它们一次应用于多个字符组的正则表达式运算符。因此,您实际上是在说:
这:
不是正则表达式保留的字符,因此它只是一个冒号。的\
是,它的意思是“下面的字符是文字,而不是一个正则表达式运算符”。这称为“转义序列”。正则表达式表示完全解析为英语
我使用的正则表达式稍微复杂一些,但还不错。让我们分解一下:^(:\(|:\))+$
。
^
和分别$
表示“行的开头”和“行的结尾”。现在我们有…
…因此它仅匹配组成整行的内容,而不仅仅是在字符串中间出现。
我们知道这一点,(
并)
表示一个分组。+
表示“其中的一个”。现在我们有:
最后是|
(管道)运算符。它的意思是“或”。因此,应用我们从上面了解的有关转义字符的知识,我们准备完成翻译:
我希望这有帮助。如果没有,请告诉我,我将很乐意通过答复来编辑我的答案。