为什么 re.search 没有得到正确的组而 re.findall 得到了正确的组?

Why is re.search not getting the right group while re.findall is getting it?

给定字符串 abc.,目的是将其分成两组 abc.。其实我只对.之前的群感兴趣。

>>> import re
>>> text = 'abc.'
>>> re.search('^(\S+)\.$', text).group(0)
'abc.'
>>> re.findall('^(\S+)\.$', text)
['abc']

为什么 re.search 没有得到正确的组而 re.findall 得到了正确的组?

输入为 abc.def. 的另一个示例,预期输出是隔离最后的句号并得到 abc.def.。所以 re.findall 正在按需获取它:

>>> re.findall('^(\S+)\.$', text)
['abc.def']

但是 re.search 将最后一个句号归为第一组。

>>> re.search('^(\S+)\.$', text).group(0)
'abc.def.'

有没有可能re.search('^(\S+)\.$', text).group(0)到return只有abc.def?是否有一些标志需要设置?

组号从 1 开始,所以您需要 group(1)group(0) 是整个匹配文本。

因为你找错群了。第 0 组是整个匹配项,包括点。第 1 组是比赛中的第一个捕获组。 match 对象的文档中详细说明了这一点,re.search returns。如果您绝对需要 zero-based,请使用 re.search(...).groups()[0]