go语言字符串换行,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("\\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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值