1

我有一个清单。我想检查它是否包含数字

list1 = [u'Studied at ', u'South City College, Kolkata', u'Class of 2012',
u'Lives in   ', u'Calcutta, India', u'From ', u'Calcutta, India']
>>> if re.match(r'[\w-]+$', str(list1)):
    print "contains a number"
else:
    print "does not contain number"

它不包含任何数字。需要一些帮助。我希望输出为“2012”

4

2 回答 2

5

\d正则表达式怎么样?

>>> import re
>>> l = [u'Studied at ', u'South City College, Kolkata', u'Class of 2012', u'Lives in ', u'Calcutta, India', u'From ', u'Calcutta, India']
>>> digit_re = re.compile('\d')
>>> [item for item in l if digit_re.search(item)]
[u'Class of 2012']

或者,如果你想提取数字:

>>> for item in l:
...     match = digit_re.search(item)
...     if match:
...         print "%s: %s" % (item, match.group(1))
... 
Class of 2012: 2012
于 2013-09-04T13:14:55.297 回答
4

只需re.search为模式做一个\d。不要re.match,那只匹配从字符串的开头。

于 2013-09-04T13:15:22.243 回答