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

4 投票
2 回答
23359 浏览
提问于 2025-04-17 16:05

我在这里看到了这些代码:

>>> 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

match.group(1) 中,1 代表什么意思呢?

相关问题:

2 个回答

4

这里的1是指在这个表达式中,括号里的组的编号。你的表达式只有一个组,但想象一下如果要把 "123 456"r"(\d+) (\d+)" 匹配起来:那么 group(1) 就会得到 "123"group(2) 会得到 "456",而 group(0) 总是匹配到整个字符串,所以它的结果是 "123 456"

12

match.group(1) 这个表达式中,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')

撰写回答