Yam*_*mel 0 regex directory path go filepath
通过使用path/filepath包含以下示例的包,您可以从文件路径获取完整目录路径.
package main
import (
"fmt"
"path/filepath"
)
func main() {
// Output: /path/to/dir
fmt.Println(filepath.Dir("/path//to/dir/file.ext"))
}
Run Code Online (Sandbox Code Playgroud)
但是有没有从路径中Parent获取的功能dir?(这是文件目录的名称):
// The `Parent` is what I want,
// and this is a pseudo-code example, this won't actually work.
//
// Output: dir
fmt.Println(filepath.Parent("/path//to/dir/file.ext"))
Run Code Online (Sandbox Code Playgroud)
如果无法使用函数完成,如何使用RegExp获取父级的名称?
您可以使用filepath.Base获取目录的最后一个元素.例如:
package main
import (
"fmt"
"path/filepath"
)
func main() {
paths := []string{
"/home/arnie/amelia.jpg",
"/mnt/photos/",
"rabbit.jpg",
"/usr/local//go",
}
for _, p := range paths {
dir := filepath.Dir(p)
parent := filepath.Base(dir)
fmt.Printf("input: %q\n\tdir: %q\n\tparent: %q\n", p, dir, parent)
}
}
Run Code Online (Sandbox Code Playgroud)
返回:
input: "/home/arnie/amelia.jpg"
dir: "/home/arnie"
parent: "arnie"
input: "/mnt/photos/"
dir: "/mnt/photos"
parent: "photos"
input: "rabbit.jpg"
dir: "."
parent: "."
input: "/usr/local//go"
dir: "/usr/local"
parent: "local"
Run Code Online (Sandbox Code Playgroud)