【问题标题】:Python regex match whole file name include file extensionPython 正则表达式匹配整个文件名包括文件扩展名
【发布时间】:2017-09-01 16:57:50
【问题描述】:

我想从标准 vsftp 日志文件中获取整个文件名和扩展名。

文件如下:

Wed Aug 31 10:23:59 2017 1 ::ffff:172.18.1.168 18593420 /Shell_Scripting.sh b _ i r user1 ftp 0 * c
Wed Aug 31 10:24:18 2017 1 ::ffff:172.18.1.168 18593420 /test.txt b _ i r user1 ftp 0 * c

我试过正则表达式

pattern = re.compile(r'\/(\w+)')
match = pattern.search(ftpfile)
print match.group(1)

但唯一匹配的文件名(Shell_Scripting & test)不包括扩展名(.sh & .txt)。

我试过re.compile(r'\/(.+\.\w+)')re.compile(r'\/(\w+\.\w+)')

他们都显示AttributeError: 'NoneType' object has no attribute 'group'

什么应该是正确的正则表达式来匹配文件名包括文件扩展名?

【问题讨论】:

  • 不要尝试正则匹配文件名。空间呢?本地文件系统允许的其他有趣的字符呢?多个.ext.ens.ions 怎么样?而是匹配到18593420的部分,然后是一组.+,然后匹配b _ i r user1 ftp 0 * c-part。
  • @user2722968 感谢提醒。是的,空格应该是个问题。我会尝试另一种方法

标签: python regex


【解决方案1】:

您可以通过简单的正则表达式使用列表推导:

import re

log = """
Wed Aug 31 10:23:59 2017 1 ::ffff:172.18.1.168 18593420 /Shell_Scripting.sh b _ i r user1 ftp 0 * c
Wed Aug 31 10:24:18 2017 1 ::ffff:172.18.1.168 18593420 /test.txt b _ i r user1 ftp 0 * c
"""

rx = re.compile(r'/(\S+)')
filenames = [match.group(1) for line in log.split("\n") for match in rx.finditer(line)]
print(filenames)
# ['Shell_Scripting.sh', 'test.txt']

心脏是/(\S+) 部分,它查找/,后跟至少一个非空白字符。

【讨论】:

  • 非常感谢。您的方法适用于大多数情况(多个扩展名、有趣的字符),不包括空格。我将继续尝试处理空白区域。谢谢你帮助我!
【解决方案2】:

你可以使用re.findall:

import re

s = ['Aug 31 10:23:59 2017 1 ::ffff:172.18.1.168 18593420 /Shell_Scripting.sh b _ i r user1 ftp 0 * c', 'Wed Aug 31 10:24:18 2017 1 ::ffff:172.18.1.168 18593420 /test.txt b _ i r user1 ftp 0 * c']

files = [re.findall("[a-zA-Z_]+\.\w+", i) for i in s]

new_files = [i[0] for i in files if i]

输出:

['Shell_Scripting.sh', 'test.txt']

【讨论】:

    【解决方案3】:

    如果你只处理 shtxt 文件,你可以这样做:

    pattern = re.compile(r'\/(\w+\.(?:txt|sh))')
    

    【讨论】:

    • 编辑:这是对现已删除的评论的回应:afaik \w 将匹配下划线/为我做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 2012-06-05
    • 2013-10-16
    • 1970-01-01
    相关资源
    最近更新 更多