问题描述

我一直试图读取文件,然后将读取的内容放入字符串中.然后,该字符串将按行拆分为多个字符串:

I've been trying to have a File be read, which will then put the read material into a string. Then the string will get split by line into multiple strings:

absPath, _ := filepath.Abs("../Go/input.txt")
data, err := ioutil.ReadFile(absPath)
if err != nil {
    panic(err)
}
input := string(data)

input.txt读取为:

The input.txt is read as:

a

强壮的小鸟

非常

大心

一天上学,

忘记了他的食物

但是

re = regexp.MustCompile("\\n")
input = re.ReplaceAllString(input, " ")

将文本弄成乱七八糟的东西:

turns the text into a mangled mess of:

在和他的食物后

homeot his food atand

我不确定替换换行符会如何严重地混乱到文本自身反转的程度

I'm not sure how replacing newlines can mess up so badly to the point where the text inverts itself

推荐答案

\n\r\r\n\n
\n\r\r\n\n
re = regexp.MustCompile(`\r?\n`)
input = re.ReplaceAllString(input, " ")

反引号将确保您不需要在正则表达式中引用反斜杠.我将问号用于回车,以确保您的代码也可以在其他平台上使用.

The backticks will make sure that you don't need to quote the backslashes in the regular expression. I used the question mark for the carriage return to make sure that your code works on other platforms as well.

这篇关于Golang:替换文本文件中字符串中的换行符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!