Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang idiomatic way to remove a blank line from a multi-line string

Tags:

string

replace

go

If I have a multi line string like

this is a line

this is another line

what is the best way to remove the empty line? I could make it work by splitting, iterating, and doing a condition check, but is there a better way?

like image 262
scott Avatar asked Feb 12 '16 10:02

scott


People also ask

How do you replace a blank line?

Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box. Click the Replace All button to replace all blank lines.

How do you write multi line string in Golang?

Creating a multiline string in Go is actually incredibly easy. Simply use the backtick ( ` ) character when declaring or assigning your string value. str := `This is a multiline string.


3 Answers

Similar to ΔλЛ's answer it can be done with strings.Replace:

func Replace(s, old, new string, n int) string Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

package main

import (
    "fmt"
    "strings"
)

func main() {

    var s = `line 1
line 2

line 3`

    s = strings.Replace(s, "\n\n", "\n", -1)

    fmt.Println(s)
}

https://play.golang.org/p/lu5UI74SLo

like image 84
plamer Avatar answered Oct 13 '22 01:10

plamer


Assumming that you want to have the same string with empty lines removed as an output, I would use regular expressions:

import (
    "fmt"
    "regexp"
)

func main() {

    var s = `line 1
line 2

line 3`

    regex, err := regexp.Compile("\n\n")
    if err != nil {
        return
    }
    s = regex.ReplaceAllString(s, "\n")

    fmt.Println(s)
}
like image 33
syntagma Avatar answered Oct 13 '22 00:10

syntagma


The more generic approach would be something like this maybe.

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    s := `


    #### 

    ####




    ####


    ####




    `

    fmt.Println(regexp.MustCompile(`[\t\r\n]+`).ReplaceAllString(strings.TrimSpace(s), "\n"))
}

https://play.golang.org/p/uWyHfUIDw-o

like image 41
xh3b4sd Avatar answered Oct 13 '22 00:10

xh3b4sd