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

huangapple go评论85阅读模式
英文:

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

问题

我一直在尝试读取一个文件,并将读取的内容放入一个字符串中。然后,这个字符串将按行分割成多个字符串:

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

input.txt 的内容如下:

a

strong little bird

with a very

big heart

went

to school one day and

forgot his food at

home

然而,

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

将文本变成了一团糟:

homeot his food atand

我不确定为什么替换换行符会导致文本混乱到翻转的程度。

英文:

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:

> 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

答案1

得分: 46

我猜你正在使用Windows运行代码。请注意,如果你打印出结果字符串的长度,它会显示超过100个字符。原因是Windows不仅使用换行符(\n),还使用回车符(\r),所以Windows中的换行实际上是\r\n,而不是\n。为了正确过滤掉字符串中的回车符,可以使用以下代码:

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

使用反引号可以确保你不需要在正则表达式中引用反斜杠。我在回车符前使用了问号,以确保你的代码在其他平台上也能正常工作。

英文:

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.

答案2

得分: 8

我认为你不需要使用正则表达式来完成这样一个简单的任务。只需使用以下代码即可实现:

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

这段代码的作用是读取文件并将其中的换行符\n替换为空字符串。你可以参考这个链接中的示例来了解如何移除\n

英文:

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)

<kbd>example of removing \n</kbd>

huangapple
  • 本文由 发表于 2015年12月6日 07:58:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/34112382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定