将行结尾转换为 "\n" 文字
Convert line endings to "\n" literals
我有一个有趣的问题要解决。由于我必须与之交谈的工具,我需要将换行符转换为文字字符串 \n
我有以下数据
{"name": 2019-05-25,
"tracker": {
"project": {
"uri": "/project/87",
"name": "Allen's Test"
},
"uri": "/tracker/57483",
"name": "Tasks"
},
"description": "[{Table
||Stack
||Current Version
||New Version
||Changes
|common
|1.0.214
|1.0.214
|* blah - [#345|https://blah.com/345]
|workflow
|2.2.23
|2.2.23
|* [ES-12345] blah - [#1087|https://blah.com/1087]
}]",
"descFormat": "Wiki"}
所以基本上不是多行字符串,我需要将它转换为带有 \n 的单行字符串,后端的工具将在其中转换它。我正在使用 go 但不太确定从哪里开始。我假设我需要原始字符串,但许多源位是 api 调用,内置了换行符。
如有任何帮助,我们将不胜感激。
我感觉这是一个 XY 问题...
但要简单地用 2 个字符的字符串 \n
替换换行符字节 '\n',请使用:
strings.ReplaceAll(data, "\n", "\n")
游乐场:https://play.golang.org/p/Xmg4pgqFy5O
输出:
{"name": 2019-05-25,\n"tracker": {\n"project": {\n "uri": "/project/87",\n ....
注意:这不处理其他格式字符,例如制表符(\t
)carriage-return( \r
) 等等
例如,
package main
import (
"fmt"
"strings"
)
func main() {
s := `"project": {
"uri": "/project/87",
"name": "Allen's Test"
},`
fmt.Println(s)
s = strings.ReplaceAll(s, "\n", `\n`)
fmt.Println(s)
}
游乐场:https://play.golang.org/p/lKZw78yOuMc
输出:
"project": {
"uri": "/project/87",
"name": "Allen's Test"
},
"project": {\n "uri": "/project/87",\n "name": "Allen's Test"\n},
对于 Go 1.12 之前,写:
s = strings.Replace(s, "\n", `\n`, -1)
我有一个有趣的问题要解决。由于我必须与之交谈的工具,我需要将换行符转换为文字字符串 \n
我有以下数据
{"name": 2019-05-25,
"tracker": {
"project": {
"uri": "/project/87",
"name": "Allen's Test"
},
"uri": "/tracker/57483",
"name": "Tasks"
},
"description": "[{Table
||Stack
||Current Version
||New Version
||Changes
|common
|1.0.214
|1.0.214
|* blah - [#345|https://blah.com/345]
|workflow
|2.2.23
|2.2.23
|* [ES-12345] blah - [#1087|https://blah.com/1087]
}]",
"descFormat": "Wiki"}
所以基本上不是多行字符串,我需要将它转换为带有 \n 的单行字符串,后端的工具将在其中转换它。我正在使用 go 但不太确定从哪里开始。我假设我需要原始字符串,但许多源位是 api 调用,内置了换行符。
如有任何帮助,我们将不胜感激。
我感觉这是一个 XY 问题...
但要简单地用 2 个字符的字符串 \n
替换换行符字节 '\n',请使用:
strings.ReplaceAll(data, "\n", "\n")
游乐场:https://play.golang.org/p/Xmg4pgqFy5O
输出:
{"name": 2019-05-25,\n"tracker": {\n"project": {\n "uri": "/project/87",\n ....
注意:这不处理其他格式字符,例如制表符(\t
)carriage-return( \r
) 等等
例如,
package main
import (
"fmt"
"strings"
)
func main() {
s := `"project": {
"uri": "/project/87",
"name": "Allen's Test"
},`
fmt.Println(s)
s = strings.ReplaceAll(s, "\n", `\n`)
fmt.Println(s)
}
游乐场:https://play.golang.org/p/lKZw78yOuMc
输出:
"project": {
"uri": "/project/87",
"name": "Allen's Test"
},
"project": {\n "uri": "/project/87",\n "name": "Allen's Test"\n},
对于 Go 1.12 之前,写:
s = strings.Replace(s, "\n", `\n`, -1)