首页 > 解决方案 > Go 标志:尾部斜杠转义 Windows 上的引号

问题描述

需要验证和清理路径的用户输入。当用户输入以下命令行时:

 app.exe -f "C:\dir with space\"

标志值的最后一个引号已转义,因此它的字符串值为:

 C:\dir with space"

你们对清理目录/路径的用户输入的干净方法有什么建议?正则表达式,或者 Go 是否有一个类似于 filepath.Clean() 的库来处理这个问题,但会删除尾随引号?

编辑:原因记录在这里: https ://github.com/golang/go/issues/16131

标签: regexgo

解决方案


例如,

package main

import (
    "fmt"
    "path/filepath"
    "runtime"
    "strings"
)

func clean(path string) string {
    if runtime.GOOS == "windows" {
        path = strings.TrimSuffix(path, `"`)
    }
    return filepath.Clean(path)
}

func main() {
    path := `C:\dir with space"`
    fmt.Println(path)
    path = clean(path)
    fmt.Println(path)
}

输出:

C:\dir with space"
C:\dir with space

参考:MSDN:Windows:命名文件、路径和命名空间


推荐阅读