【问题标题】:Regex to extract last characters after underscore of folder name of full path正则表达式提取完整路径的文件夹名称下划线后的最后一个字符
【发布时间】:2021-02-04 05:28:45
【问题描述】:

我有两个不同的正则表达式几乎可以正确完成我的任务。我实际上是在尝试像这样提取文件父文件夹的最后一个字符:

C:\home\username\folder_number_three\image.tif

three

我使用了正则表达式[^_]+$,但是这只会返回三个没有与原始字符串关联的文件名,即C:\home\username\folder_number_three

我使用此处指示的解决方案来删除文件名,但我无法将这两种解决方案结合起来:regex removing filename from path

任何帮助将不胜感激。

【问题讨论】:

    标签: regex


    【解决方案1】:

    使用

    _[^_\\.]+(?=$|\\[^_\\]+\.[^_\\]+$)
    

    proof

    说明

    --------------------------------------------------------------------------------
      _                        '_'
    --------------------------------------------------------------------------------
      [^_\\.]+                 any character except: '_', '\\', '.' (1 or
                               more times (matching the most amount
                               possible))
    --------------------------------------------------------------------------------
      (?=                      look ahead to see if there is:
    --------------------------------------------------------------------------------
        $                        before an optional \n, and the end of
                                 the string
    --------------------------------------------------------------------------------
       |                        OR
    --------------------------------------------------------------------------------
        \\                       '\'
    --------------------------------------------------------------------------------
        [^_\\]+                  any character except: '_', '\\' (1 or
                                 more times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
        \.                       '.'
    --------------------------------------------------------------------------------
        [^_\\]+                  any character except: '_', '\\' (1 or
                                 more times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
        $                        before an optional \n, and the end of
                                 the string
    --------------------------------------------------------------------------------
      )                        end of look-ahead
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多