【问题标题】:Regular expressions in Python - AttributeError: 'NoneType' object has no attribute 'group'Python 中的正则表达式 - AttributeError:“NoneType”对象没有属性“组”
【发布时间】:2018-04-19 04:57:18
【问题描述】:

我正在尝试打印以单词 first 开头的文件名。

这是我所做的:

导入操作系统 重新导入

path = '/my_path'
for root, dirs, files in os.walk(path):
    for file in files:
        match_pattern = re.search(r'^first', file)
        print match_pattern.group()

但是,这是我在运行程序时得到的:

first
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    print match_pattern.group()
AttributeError: 'NoneType' object has no attribute 'group'

我想打印出以first开头的文件名,例如:

first-xyz
first abc

我做错了什么?

【问题讨论】:

  • match_patternNone 表示您的正则表达式与文件名不匹配。为什么不使用调试器,看看file 的值是多少?
  • 我尝试打印出“文件”并返回了文件名
  • 你为什么要为此使用正则表达式?只需使用str.startswith

标签: python regex


【解决方案1】:

如果 RegEx 不匹配,则返回None,因此您需要这样修复:

match_pattern = re.search(r'^first', file)
if match_pattern:
    print match_pattern.group()

另外,请注意,在 Python 2 中,file 是一个内置函数(open 的别名),您不应重新定义。

【讨论】:

    【解决方案2】:

    您的搜索返回无。试试这个:

    path = '/my_path'
    for file in os.listdir(path):
        if file.startswith("first"):
            print file + '\n'
    

    【讨论】:

      【解决方案3】:

      如果没有匹配项 (see python.org documentation for re.search() here),Python 的正则表达式方法 re.search()re.match() 都会返回 None。在尝试使用match_pattern.group() 访问有关结果的信息之前,您需要测试结果是否为无。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-09
        • 1970-01-01
        • 1970-01-01
        • 2015-09-06
        • 1970-01-01
        • 2010-12-02
        相关资源
        最近更新 更多