Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading