【问题标题】:Lua remove first directory from pathLua从路径中删除第一个目录
【发布时间】:2021-01-30 14:30:55
【问题描述】:

如何从路径字符串中删除第一个目录(如果存在)?

我用gsubstring.match 尝试了几次,但我无法正常工作。

输入:

/
/tmp/file.txt
/tmp/folder/file2.txt
/tmp/folder/.../file3.txt

输出:

/
/file.txt
/folder/file2.txt
/folder/.../file3.txt

【问题讨论】:

    标签: lua


    【解决方案1】:
    local paths = {
        '/',
        '/tmp/file.txt',
        '/tmp/folder/file2.txt',
        '/tmp/folder/.../file3.txt'
    }
    
    for _, path in ipairs (paths) do
        local trimmed = path:gsub ('^/[^/]+', '')
        print (trimmed)
    end
    

    必要的正则表达式是^/[^/]+。它被锚定到字符串的开头,并且后面至少需要一个非斜线字符,这样/ 就不会匹配。

    【讨论】:

      【解决方案2】:
      #! /usr/bin/env lua
      
      dirsep = package .config :sub( 1, 1 )
      cwd = '/tmp/folder/file2.txt'
      delimeter = { cwd :find( dirsep, 2 ) }
      subdir = cwd :sub( delimeter [1] or 1 )
      
      print( subdir )
      

      /文件夹/file2.txt

      【讨论】:

      • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
      • 我使用了变量名来解释发生了什么。 dirsep 是目录分隔符。 cwd 是当前工作目录。分隔符从字面上找到分隔符。 subdir 是子目录。这怎么很难理解?
      • 命名良好的变量并不能说明您的代码的作用、工作方式和原因。
      猜你喜欢
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2021-01-09
      相关资源
      最近更新 更多