当re.findall()中的正则表达式包含多个括号时,返回值是一个列表,其中每个元素都是一个元组。这个元组的长度与正则表达式中括号的数量相同,元组中的每个元素都是与相应括号中的模式匹配的文本。
- import re
-
- # 定义一个包含三个括号的正则表达式
- pattern = r'(\d+)-(\w+)-(\d+)'
-
- text = '123-abc-456 789-def-1234'
-
- # 使用re.findall()查找所有匹配项
- matches = re.findall(pattern, text)
-
- print(matches)
输出:
[('123', 'abc', '456'), ('789', 'def', '1234')]