无法理解python中pattern.findall()的行为

2024-06-28 10:59:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中很幼稚,在学习Python中的re模块时,我发现了一些奇怪的东西(我无法理解):

import re

pattern = re.compile(r'[0-9]{3}-[0-9]{3}-[0-9]{4}')
list_phoneNumbers = pattern.findall('phone number : 123-456-7894, my home number : 789-456-1235')
print(list_phoneNumbers)

pattern = re.compile(r'bat(wo)?man')
batman_match = pattern.search('batman is there')
batwoman_match = pattern.search('batwoman is there')
bat_list_all = pattern.findall('batman is there but not batwoman')

print(batman_match.group())
print(batwoman_match.group())
print(bat_list_all)

输出:

['123-456-7894', '789-456-1235']
batman
batwoman
['', 'wo']

为什么print(bat_list_all)没有列出[蝙蝠侠]、[蝙蝠侠]?我缺少什么来理解


Tags: renumberismatchalllistpatternthere
1条回答
网友
1楼 · 发布于 2024-06-28 10:59:03

这是因为您正在使用组(wo)?,所以findall返回与此组匹配的内容:

  • ''代表batman
  • 'wo'代表batwoman

您可以使用non-matching group:pattern = re.compile(r'bat(?:wo)?man')


re.findall(): return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

相关问题 更多 >