Mickel
Mickel

Reputation: 6696

Golang split string by empty newline

I have this JS function that I'm trying to translate to Go:

function splitByEmptyNewline(str) {
  return str
    .replace(/\r\n/g, '\n')
    .split(/^\s*\n/gm);
}

Here's what I got so far:

func splitByEmptyNewline(str string) []string {
    strNormalized := regexp.
        MustCompile("\r\n").
        ReplaceAllString(str, "\n")
    return regexp.
        MustCompile("^s*\n").
        Split(strNormalized, -1)
}

This does not return the same result as the JavaScript version. So I'm wondering what I've missed?

I've tried using both double-quotes " and backward single-quotes ` for the regex.

Upvotes: 1

Views: 3274

Answers (1)

Andreas Koch
Andreas Koch

Reputation: 2037

Your seperator RegEx does not match because you split a complete string and the beginning of that string is not white-space. So instead of ^\s*\n you must use \n\s*\n:

func splitByEmptyNewline(str string) []string {
    strNormalized := regexp.
        MustCompile("\r\n").
        ReplaceAllString(str, "\n")

    return regexp.
        MustCompile(`\n\s*\n`).
        Split(strNormalized, -1)

}

Here here is working example: https://play.golang.org/p/be6Mf3-XNP

Upvotes: 2

Related Questions