1

我在这里遇到了代码:

>>> import urllib, re
>>> prefix = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
>>> findnothing = re.compile(r"nothing is (\d+)").search
>>> nothing = '12345'
>>> while True:
...     text = urllib.urlopen(prefix + nothing).read()
...     print text
...     match = findnothing(text)
...     if match:
...         nothing = match.group(1)
...         print "   going to", nothing
...     else:
...         break

1in是什么match.group(1)意思?

4

2 回答 2

7

1inmatch.group(1)代表第一个带括号的子组。在你的情况下,第一个。

这在官方文档中有很好的描述,re.MatchObject.group()并通过一个示例进行了最佳说明:

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'
>>> m.group(2)       # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2)    # Multiple arguments give us a tuple.
('Isaac', 'Newton')
于 2013-02-16T11:34:17.143 回答
3

1 是表达式中组的编号(由括号对表示)。您的表达式只有一组,但想象匹配: will be , will be"123 456"并且始终是整个匹配项,因此.r"(\d+) (\d+)"group(1)"123"group(2)"456"group(0)"123 456"

于 2013-02-16T11:32:49.323 回答