【问题标题】:Not able to understand behavior of pattern.findall() in python [duplicate]无法理解 python 中 pattern.findall() 的行为 [重复]
【发布时间】:2020-03-08 08:36:04
【问题描述】:

在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)怎么没给列表['batman','batwoman']?我想了解什么?

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

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

    • ''batman
    • 'wo'batwoman

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


    re.findall():返回字符串中所有不重叠的模式匹配,作为字符串列表。从左到右扫描字符串,并按找到的顺序返回匹配项。 如果模式中存在一个或多个组,则返回组列表;如果模式有多个组,这将是一个元组列表。结果中包含空匹配项。

    【讨论】:

    • 我想(wo)?表示 0 或 1 次出现 wo。感谢您关注小组。
    • @RaviJiyani 确实如此,但括号也构成了一个捕获组,可以使用 findall for ex 进行检索
    • 是的,刚刚浏览了文档: (?:...) 常规括号的非捕获版本。匹配括号内的任何正则表达式,但组匹配的子字符串在执行匹配后无法检索或稍后在模式中引用。
    猜你喜欢
    • 2019-09-07
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2014-06-08
    • 2016-09-01
    • 2013-12-28
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多