当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO Clean用法及代码示例


GO语言"path"包中"Clean"函数的用法及代码示例。

用法:

func Clean(path string) string

Clean 通过纯词法处理返回与 path 等效的最短路径名。它迭代地应用以下规则,直到无法进行进一步处理:

1. Replace multiple slashes with a single slash.
2. Eliminate each . path name element (the current directory).
3. Eliminate each inner .. path name element (the parent directory)
   along with the non-.. element that precedes it.
4. Eliminate .. elements that begin a rooted path:
   that is, replace "/.." by "/" at the beginning of a path.

仅当返回的路径是根 "/" 时,返回的路径才以斜线结尾。

如果此过程的结果是空字符串,则 Clean 返回字符串 "."。

另请参见 Rob Pike,“计划 9 中的词法文件名或获取 Dot-Dot 正确”,https://9p.io/sys/doc/lexnames.html

例子:

package main

import (
	"fmt"
	"path"
)

func main() {
	paths := []string{
		"a/c",
		"a//c",
		"a/c/.",
		"a/c/b/..",
		"/../a/c",
		"/../a/b/../././/c",
		"",
	}

	for _, p := range paths {
		fmt.Printf("Clean(%q) = %q\n", p, path.Clean(p))
	}

}

输出:

Clean("a/c") = "a/c"
Clean("a//c") = "a/c"
Clean("a/c/.") = "a/c"
Clean("a/c/b/..") = "a/c"
Clean("/../a/c") = "/a/c"
Clean("/../a/b/../././/c") = "/a/c"
Clean("") = "."

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Clean。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。