代码之家  ›  专栏  ›  技术社区  ›  user9431057

提取文件名中第一个出现的数字和最后一个单词

  •  2
  • user9431057  · 技术社区  · 7 年前

    filenames = ['122 CHC Sep 2017.xlsx', '124 CHC Sep 2017 RFK.xlsx', '124 CHC Sep 2018 Trc.xlsx']
    

    我要第一个数字和最后一个单词。

    我的输出需要这样,

    ['122', '124 RFK', '124 Trc']
    

    我试过以下方法,

    regex = re.compile(r'^\D*(\d+)([a-zA-Z]+)\.[a-zA-Z]+$') 
    [regex.findall(x) for x in filenames]
    

    [['122'],['124'], ['124']]
    

    regex = re.compile(r'^\D*(\d+).*?([a-zA-Z]+)\.[a-zA-Z]+$')
    [regex.findall(x) for x in filenames]
    

    我要走了,

    [[], ['124', 'RFK'], ['124', 'Trc']]
    

    这一次我不想 122 .

    (注意:如果有一种方法可以将所有字母大写,然后使用regex,那就太棒了)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Wiktor Stribiżew    7 年前

    你可以用

    ^\D*(\d+)(?:.*?(\s*[a-zA-Z]+)|.*)\.[a-zA-Z]+$
    

    regex demo .

    细节

    • ^
    • \D* -0+非数字
    • (\d+) -第1组:一个或多个数字
    • (?:.*?(\s*[a-zA-Z]+)|.*) -两种选择之一:
      • .*?(\s*[a-zA-Z]+)
      • | -或者
      • .* -任何0+字符,尽可能多
    • \. - [a-zA-Z]+
    • $ -字符串结尾。

    下面是 Python demo :

    import re
    filenames = ['122 CHC Sep 2017.xlsx', '124 CHC Sep 2017 RFK.xlsx', '124 CHC Sep 2018 Trc.xlsx']
    rx = re.compile(r'^\D*(\d+)(?:.*?(\s*[a-zA-Z]+)|.*)\.[a-zA-Z]+$')
    print([rx.sub(r'\1\2', x) for x in filenames])
    # => ['122', '124 RFK', '124 Trc']