'How to remove multiple line break `\n` from a string but keep only one?
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
Solution 1:[1]
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"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | The Fool |
