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?
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.
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.
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
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)
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With