开始-是否可以将原始字符串文字转换为解释的字符串文字?

问题描述

在Go中是否可以将原始字符串文字转换为解释的字符串文字? (请参见language specification

我有一个原始的字符串文字,但是我想在控制台上打印出解释后的字符串文字会得到的结果,即使用转义序列格式化的文本输出

例如,打印此原始字符串文字会得到

s := `\033[1mString in bold.\033[0m`
println(s) // \033[1mString in bold.\033[0m

但是我希望得到相同的结果

s := "\033[1mString in bold.\033[0m"
println(s) // String in bold. (In bold)

对于上下文,我正在尝试打印文本文件内容,该文件使用转义序列进行格式化

f,_ := := IoUtil.ReadFile("file.txt")
println(string(f))

但是输出是前一种方式。

解决方法

使用strconv.Unquote()

s := `\033[1mString in bold.\033[0m`

s2,err := strconv.Unquote(`"` + s + `"`)
if err != nil {
    panic(err)
}
fmt.Println("normal",s2)

这将输出:

正常粗体字符串。

请注意,传递给string的{​​{1}}值必须包含换行双引号或反引号,并且由于源strconv.Unquote()不包含换行双引号,因此我在其前加后缀这个:

s

查看相关问题:

How do I make raw unicode encoded content readable?

Golang convert integer to unicode character

How to transform Go string literal code to its value?

How to convert escape characters in HTML tags?