Home > Net >  How to remove multiple line break `\n` from a string but keep only one?
How to remove multiple line break `\n` from a string but keep only one?

Time:04-23

At JavaScript, I was using this Regexp to replace multiple line break with one str.replace(/(\r\n?|\n){2,}/g, '$1') but for golang I am not sure what it will be. How can I achieve this in golang?

Input:

Some string\n\n\n\n\n\nFoo bar Step1:\n\nFoo bar Step2:\n\n\nFoo bar final

Output

Some string\nFoo bar Step1:\nFoo bar Step2:\nFoo bar final

CodePudding user response:

You can do the same.

rg := regexp.MustCompile(`(\r\n?|\n){2,}`)
s := "Some string\n\n\n\n\n\nFoo bar Step1:\n\nFoo bar Step2:\n\n\nFoo bar final"
result := rg.ReplaceAllString(s, "$1")
fmt.Printf("%q", result)
// "Some string\nFoo bar Step1:\nFoo bar Step2:\nFoo bar final"

https://go.dev/play/p/u-mfj7tXctO

  • Related