Python 正则表达式组

标签 python regex python-2.7

为什么这个正则表达式会打印 ('c',)()? 我认为“([abc])+”===“([abc])([abc])([abc])...”

>>> import re
>>> m = re.match("([abc])+", "abc")
>>> print m.groups()
('c',)
>>> m.groups(0)
('c',)
>>> m = re.match("[abc]+", "abc")
>>> m.groups()
()
>>> m.groups(0)
()

最佳答案

来自有关的文档 groups

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None.

在第一个正则表达式([abc])+中,它匹配字符abc 但只会存储最后一场比赛

([abc])+
<----->
Matches a or b or c
Observe carefully. Capturing groups are surrounding only the character class
So, only one character from the matched character class can be stored in capturing group.

如果您想在捕获组中捕获字符串abc,请使用

([abc]+)

Above will find string composed of a or b or c and will store it in capturing group.

在第二个正则表达式 [abc]+ 中,没有捕获组,因此显示空结果。

关于Python 正则表达式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38216055/

相关文章:

python - 当绘制在强度之上时,颤抖图会发生变化

python - 在函数内的 for 循环上使用 tqdm 来检查进度

regex - 如何用R中的 "something plus special characters"替换许多特殊字符

python - 将帖子标题转换为 CamelCase

python-2.7 - functools.wrapper - AttributeError : attribute '__doc__' of 'type' objects is not writable

python - Pillow (PIL) 到 QImage 的转换 -> python.exe 已停止工作

python - 在 Django 管理站点中显示 ManyToMany 对象的字段名称而不是整个对象

python - 在字典中访问 Pandas 面具

python - Python 中的正则表达式

python - 正则表达式返回匹配和扩展匹配