dtqi87613
2019-01-10 12:02
浏览 59
已采纳

如何使用golang替换字符串

I am Making a command line tool for sending an email where I am using urfave/cli package from golang i had made the application where everything is working properly but got stuck with one string replacement part.

Basically, I want to convert a string

info@gmail.com,vik@hotmail.com,myemailid@yahoo.com

to

"info@gmail.com","vik@hotmail.com","myemailid@yahoo.com"

I tried regex substitution but that didn't give me an accurate result. so I manipulate my code where I used String.Split separated by ',' but after that the look around got complex. can anyone help me with this

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

我正在制作一个命令行工具,用于在使用 urfave / cli 软件包使该应用程序的所有功能均正常运行,但卡在了一个字符串替换部分上。

基本上,我想转换一个字符串

info @ gmail.com,vik @ hotmail.com, myemailid@yahoo.com

“ info@gmail.com” ,“ vik@hotmail.com”,“ myemailid@yahoo.com”

我尝试了正则表达式替换,但是并没有给出准确的结果。 因此我在使用以','分隔的 String.Split 的地方操作了我的代码,但是之后情况变得复杂了。 有人可以帮我吗

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

1条回答 默认 最新

  • dongmiao4733 2019-01-10 12:12
    已采纳

    To convert the value, simply run something like:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        input := "info@gmail.com,vik@hotmail.com,myemailid@yahoo.com"
        emails := strings.Join(Map(strings.Split(input, ","), func(in string) string {
            return fmt.Sprintf(`"%s"`, in)
        }), ",")
    
        fmt.Printf("%v", emails)
    }
    
    func Map(vs []string, f func(string) string) []string {
        vsm := make([]string, len(vs))
        for i, v := range vs {
            vsm[i] = f(v)
        }
        return vsm
    }
    

    https://play.golang.org/p/M0xfCkpT6uD

    Good luck.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题