Golang惯用方式从多行字符串中删除空白行 [英] Golang idiomatic way to remove a blank line from a multi-line string

查看:189
本文介绍了Golang惯用方式从多行字符串中删除空白行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有多行字符串,例如

If I have a multi line string like

this is a line

this is another line

删除空行的最佳方法是什么?我可以通过拆分,迭代和进行条件检查来使其工作,但是还有更好的方法吗?

what is the best way to remove the empty line? I could make it work by splitting, iterating, and doing a condition check, but is there a better way?

推荐答案

假定您要删除输出的空行作为输出的相同字符串,我将使用正则表达式:

Assumming that you want to have the same string with empty lines removed as an output, I would use regular expressions:

import (
    "fmt"
    "regexp"
)

func main() {

    var s = `line 1
line 2

line 3`

    regex, err := regexp.Compile("\n\n")
    if err != nil {
        return
    }
    s = regex.ReplaceAllString(s, "\n")

    fmt.Println(s)
}

这篇关于Golang惯用方式从多行字符串中删除空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆