douzhi1937
2016-04-30 16:42
浏览 1.9k
已采纳

Golang用空换行符分割字符串

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

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

Here's what I got so far:

func splitByEmptyNewline(str string) []string {
    strNormalized := regexp.
        MustCompile("
").
        ReplaceAllString(str, "
")
    return regexp.
        MustCompile("^s*
").
        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.

图片转代码服务由CSDN问答提供 功能建议

我有这个JS函数,我想将其转换为Go: < pre> 函数splitByEmptyNewline(str){ 返回str .replace(/ / g,' ') .split(/ ^ \ s * / gm); \ n}

这是我到目前为止得到的:

  func splitByEmptyNewline(str string)[] string {  
 strNormalized:=正则表达式。
 MustCompile(“ 
 
”)。
 ReplaceAllString(str,“ 
”)
返回正则表达式。
 MustCompile(“ ^ s * 
”)。
  Split(strNormalized,-1)
} 
   
 
 

这不会返回与JavaScript版本相同的结果。 所以我想知道我错过了什么吗?

我尝试同时使用双引号和后引单引号`

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqphg40600 2016-04-30 17:46
    已采纳

    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* you must use \s* :

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

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

    打赏 评论

相关推荐 更多相似问题