检查正则表达式是否返回None

时间:2014-07-06 12:36:39

标签: python regex

大家好,我正在pythonchallenge.com上进行python挑战,目前我正在挑战4.我有以下代码:

import urllib,re
number = 12345
url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=' + str(number)
page = urllib.urlopen(url)

def nextNumber(site):
    contents = page.read()
    decimal = re.search(r'\d+', contents).group()
    while decimal in contents and decimal: 
        new_url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=' +      str(decimal) 
        print new_url
        page2 = urllib.urlopen(new_url)
        contents = page2.read()
        decimal = re.search(r'\d+', contents).group()
nextNumber(url)

我遇到的问题是,当我到达号码16044时,该站点说我必须将它除以2,因此十进制等于None,这会产生错误。我尝试用一​​些if语句解决它:

if decimal is None:
    print "hi"

但我仍然收到此错误。

1 个答案:

答案 0 :(得分:1)

您的问题出现在此声明中(在while循环中):

decimal = re.search(r'\d+', contents).group()
如果未找到匹配项,

re.search将返回None。

请改为尝试:

decimal = re.search(r'\d+', contents)
if decimal:
  decimal = decimal.group()
else:
  # do something else
相关问题