登录
首页 >  Golang >  Go问答

将带有字符串键/值的文件转换为 Go 映射

来源:stackoverflow

时间:2024-03-31 10:18:34 287浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《将带有字符串键/值的文件转换为 Go 映射》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我有一个文件,其中包含由 = 符号分隔的字符串键/值对。它看起来像这样:

"some.key" = "a cool value.";
"some.other.key" = "a cool value with %@ chars and \n. another thing.";
"escaped.key" = "a cool \"value\".";
"multiline.key.value" = "1. first sentence is "cool"\
2. second sentence\
3. third sentence\
4. fourth sentence";

请注意,值内部可以包含转义引号,并且它们也可以跨越多行。

我已经尝试过基本的引号匹配,但它不能处理值中的转义引号等...这是我目前正在尝试的:

file, err := ioutil.ReadFile("/my/string/file")
if err != nil {
    log.Fatal(err)
}

re := regexp.MustCompile(`".*?"`)
match := re.FindAllString(string(file), -1)
fmt.Println(match)

如有任何帮助,我们将不胜感激:d


解决方案


另一种方法 - 您可以使用带有自定义 split function 的扫描仪来按对分隔符 ; 进行分割并扫描每个单独的密钥对。然后用“-”分割键值对文本以分割键和值。

file, err := os.open("/my/string/file")
if err != nil {
    log.fatal(err)
}
defer f.close()

scanner := bufio.newscanner(f)
scanner.split(customsplitfunc)
for scanner.scan() {
    fmt.println("key-value pair: ", scanner.text())
    //split scanner.text() by "=" to split key and value
}

并定义customsplitfunc如下

func customsplitfunc(data []byte, ateof bool) (advance int, token []byte, err error) {
    if ateof && len(data) == 0 {
        return 0, nil, nil
    }

    if ateof {
        return len(data), data, nil
    }

    //; followed by newline is the k-v pair delimiter
    if i := strings.index(string(data), ";\n"); i >= 0 {
        //skip the delimiter in advancing to the next pair
        return i + 2, data[0:i], nil
    }
    return
}

我认为 (?m)^"([^"]+)"\s*=\s*"(([^"]|(\\")|(\\\n))+ )";$ 做你想要的。 将其与 findallstringsubmatch 一起使用,它将返回所有匹配对。请注意,如果任何输入的语法无效,则整个内容将不匹配,因此这可能不完全是您想要的。

func main() {
    re := regexp.MustCompile(`(?m)^"([^"]+)"\s*=\s*"(([^"]|(\\")|(\\\n))+)";$`)
    matches := re.FindAllStringSubmatch(`"some.key" = "A cool value.";
"some.other.key" = "A cool value with %@ chars and \n. Another Thing.";
"escaped.key" = "A cool \"value\".";
"multiline.key.value" = "1. First sentence is \"cool\"\
2. Second sentence\
3. Third sentence\
4. Fourth sentence";
`, -1)
    for _, m := range matches {
        fmt.Printf("%q %q\n", m[1], m[2])
    }
}

(我在您输入的第四行添加了缺少的反斜杠。)

请参阅 https://play.golang.org/p/ZHV8jpg17nY

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将带有字符串键/值的文件转换为 Go 映射》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>