【问题标题】:Regex to find date format from a string [closed]正则表达式从字符串中查找日期格式[关闭]
【发布时间】:2021-01-05 05:08:03
【问题描述】:

我有不同的路径,我必须使用正则表达式从路径中找到日期并将其附加到文件名。

Input:

/hash/20190811T003013/ABC.txt

Expected Output:
ABC_20190811T003013.txt

【问题讨论】:

    标签: python regex date


    【解决方案1】:

    re.findall的解决方案:

    import re
    s = '/hash/20190811T003013/ABC.txt'
    re.findall('(\w+).txt', s)[0] + '_' + re.findall('(\d{8}\w+)', s)[0] + re.findall('(\.\w+)', s)[0]
    'ABC_20190811T003013.txt'
    

    【讨论】:

      【解决方案2】:

      尝试将str.joinmapstr.split 一起使用:

      s = '/hash/20190811T003013/ABC.txt'
      _, b, c, d = s.split('/')
      print('_'.join(d.split('.')[0], c) + '.txt')
      

      输出:

      ABC_20190811T003013.txt
      

      【讨论】:

      • 如何让它更通用而不是在文件路径@U11-Forward中寻找日期的位置
      • @hashalluring 好的,我会编辑
      • @hashalluring 编辑了我的答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      相关资源
      最近更新 更多