Golang: problems replacing newlines in a line from a text file

I am trying to read a file, which then puts the read material into a line. Then the line will be divided into lines into several lines:

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

Input.txt reads as:

a

strong little bird

with very

a big heart

went

to school one day and

forgot about food in

home

but

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

turns text into a distorted mess:

Homeop of his food and

I'm not sure how replacing newlines can go so bad that the text inverts itself

+6
source share
2 answers

I assume that you are using code using Windows. Please note that if you print the length of the resulting string, it will display more than 100 characters. The reason is that Windows not only uses newlines ( \n ), but it also returns carriage returns ( \r ), so on Windows it’s actually \r\n , not \n . To filter them correctly from your string, use:

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

Back tags will ensure that you don't need to specify a backslash in a regular expression. I used a question mark to return a carriage to make sure your code works on other platforms as well.

+10
source

I don’t think you need to use regex for such a simple task. This can only be achieved with

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

delete example \ n

+1
source

All Articles