为什么 re.groups() 不会为我的一个正确匹配的组提供任何信息?
当我运行此代码时:
print re.search(r'1', '1').groups()
我得到 ()
的结果。然而, .group(0)
给了我匹配。
groups()
不应该给我包含匹配项的内容吗?
When I run this code:
print re.search(r'1', '1').groups()
I get a result of ()
. However, .group(0)
gives me the match.
Shouldn't groups()
give me something containing the match?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,
.groups()
返回一个记住的组的元组。即正则表达式中用括号括起来的那些组。所以如果你写:你会得到
你的回应。一般来说,
.groups()
将返回正则表达式中括号内的所有对象组的元组。To the best of my knowledge,
.groups()
returns a tuple of remembered groups. I.e. those groups in the regular expression that are enclosed in parentheses. So if you were to write:you would get
as your response. In general,
.groups()
will return a tuple of all the groups of objects in the regular expression that are enclosed within parentheses.groups 为空,因为您没有任何捕获组 - http://docs.python.org/库/re.html#re.MatchObject.groups。 group(0) 将始终返回匹配的整个文本,无论它是在组中捕获还是未
编辑。
groups is empty since you do not have any capturing groups - http://docs.python.org/library/re.html#re.MatchObject.groups. group(0) will always returns the whole text that was matched regardless of if it was captured in a group or not
Edited.
您的正则表达式中没有组,因此您会得到一个空列表 (
()
)。尝试
使用括号创建一个捕获组,与模式的这一部分相匹配的结果将存储在一个组中。
然后你就得到
结果了。
You have no groups in your regex, therefore you get an empty list (
()
) as result.Try
With the brackets you are creating a capturing group, the result that matches this part of the pattern, is stored in a group.
Then you get
as result.
原因是您没有捕获组(因为您在模式中没有使用
()
)。http://docs.python.org/library/re.html#re .MatchObject.groups
和
group(0)
返回整个搜索结果(即使它根本没有捕获组):http://docs.python.org/library/re.html#re .MatchObject.group
The reason for this is that you have no capturing groups (since you don't use
()
in the pattern).http://docs.python.org/library/re.html#re.MatchObject.groups
And
group(0)
returns the entire search result (even if it has no capturing groups at all):http://docs.python.org/library/re.html#re.MatchObject.group