string Golang:从文本文件中替换字符串中的换行符的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34112382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:29:04  来源:igfitidea点击:

Golang: Issues replacing newlines in a string from a text file

stringfileinputgonewline

提问by Orange Receptacle

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)

The input.txt is read as:

input.txt 读作:

a

strong little bird

with a very

big heart

went

to school one day and

forgot his food at

home

一种

坚强的小鸟

与一个非常

宽容的心

有一天去学校

忘记了他的食物

However,

然而,

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

我不确定如何替换换行符会如此糟糕到文本反转的程度

回答by Jens Grabarske

I guess that you are running the code using Windows. Observe that if you print out the length of the resulting string, it will show something over 100 characters. The reason is that Windows uses not only newlines (\n) but also carriage returns (\r) - so a newline in Windows is actually \r\n, not \n. To properly filter them out of your string, use:

我猜您正在使用 Windows 运行代码。请注意,如果您打印出结果字符串的长度,它将显示超过 100 个字符的内容。原因是 Windows 不仅使用换行符 ( \n) 还使用回车符 ( \r) - 所以 Windows 中的换行符实际上\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.

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

回答by Salvador Dali

I do not think that you need to use regex for such an easy task. This can be achieved with just

我认为您不需要使用正则表达式来完成如此简单的任务。这可以通过

absPath, _ := filepath.Abs("../Go/input.txt")
data, _ := ioutil.ReadFile(absPath)
input := string(data)
strings.Replace(input, "\n","",-1)

example of removing \n

example of removing \n