Golang:替换文本文件中字符串中的换行符的问题 [英] Golang: Issues replacing newlines in a string from a text file

查看:1358
本文介绍了Golang:替换文本文件中字符串中的换行符的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

我猜您正在使用Windows运行代码.注意,如果您打印出结果字符串的长度,它将显示超过100个字符.原因是Windows不仅使用换行符(\n),而且还使用回车符(\r)-因此Windows中的换行符实际上是\r\n,而不是\n.要从字符串中正确过滤掉它们,请使用:

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:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆