【发布时间】:2009-11-11 11:24:30
【问题描述】:
我需要能够区分可以包含字母和数字的字符串与可以包含数字、冒号和连字符的字符串之间的区别 。
>>> def checkString(s):
... pattern = r'[-:0-9]'
... if re.search(pattern,s):
... print "Matches pattern."
... else:
... print "Does not match pattern."
# 3 Numbers seperated by colons. 12, 24 and minus 14
>>> s1 = "12:24:-14"
# String containing letters and string containing letters/numbers.
>>> s2 = "hello"
>>> s3 = "hello2"
当我对上述每个字符串运行checkString 方法时:
>>>checkString(s1)
Matches Pattern.
>>>checkString(s2)
Does not match Pattern.
>>>checkString(s3)
Matches Pattern
s3 是唯一不做我想做的事的人。我希望能够创建一个允许数字、冒号和连字符的正则表达式,但不包括其他所有内容(或只是字母字符)。谁能指出我正确的方向?
编辑:
因此,我需要一个可以接受的正则表达式:
229 // number
187:657 //two numbers
187:678:-765 // two pos and 1 neg numbers
然后拒绝:
Car //characters
Car2 //characters and numbers
【问题讨论】:
-
你想肯定匹配字母+数字的东西,还是不想?您在开头声明匹配字母+数字,但随后您说您不想匹配 s3(但您确实想匹配 s2)。