dshtze500055 2015-12-05 23:58
浏览 948
已采纳

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)

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("\
")
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

  • 写回答

2条回答 默认 最新

  • doushe8577 2015-12-06 00:15
    关注

    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 ( ) but also carriage returns () - so a newline in Windows is actually , not . To properly filter them out of your string, use:

    re = regexp.MustCompile(`?
    `)
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败