regex - 使用正则表达式将字符串包含到另一个字符串中

标签 regex go

我有一些弦乐。字符串可能在方括号之间列出了项目。我想在括号内的字符串中包含一定数量的额外项目。括号可能是空的或不存在。例如:

  • string1-> string1#没有添加任何内容
  • string2 []-> string2 [extra1 =“1”,extra2 =“2”]#添加了两项
  • string3 [item =“1”]-> string3 [item =“1”,extra1 =“1”,extra2 =“2”]#添加了两项

  • 目前,我通过以下代码(Golang)实现此目标:
    str1 := "test"
    str2 := `test[]`
    str3 := `test[item1="1"]`
        
    re := regexp.MustCompile(`\[(.+)?\]`)
    
    for _, s := range []string{str1, str2, str3} {
        s = re.ReplaceAllString(s, fmt.Sprintf(`[item1="a",item2="b",$1]`))
        fmt.Println(s)
    }
    
    但是在输出中,如果括号为空,最后我还会得到一个不必要的逗号“,”:
    test
    test[item1="a",item2="b",]
    test[item1="a",item2="b",item1="1"]
    
    如果没有括号,是否可以避免使用逗号分隔?
    当然,可以再次解析字符串并修剪逗号,但这似乎不是最佳选择。
    Code example on Go playground

    最佳答案

    您可以有两个正则表达式,其中一个匹配空[],另一个匹配
    匹配[]中带有文本的字符串。以下是经过测试的代码-
    https://play.golang.org/p/_DOOGDMUOCm
    第二种方法是在替换字符串后回头看一看。如果
    最后两个字符是,],您可以将其子串化为,然后添加]。一世
    猜猜您已经知道这种方法。

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        str1 := "test"
        str2 := `test[]`
        str3 := `test[item1="1"]`
        
        re := regexp.MustCompile(`\[(.*)\]`)
    
        for _, s := range []string{str1, str2, str3} {
           matched,err := regexp.Match(`\[(.+)\]`, []byte(s));
           _ = err;
           if(matched==true){
              s = re.ReplaceAllString(s, fmt.Sprintf(`[item1="a",item2="b",$1]`));
           }else {
              s = re.ReplaceAllString(s, fmt.Sprintf(`[item1="a",item2="b"]`));
           }
           fmt.Println(s)
        }
    }
    

    关于regex - 使用正则表达式将字符串包含到另一个字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63382199/

    相关文章:

    Java RegEx转义重复的单引号

    php - 如何在 MySQL 查询中使用正则表达式?

    c# - 解析字符串中的名称

    go - 为什么 go get -u 在模块目录中需要很长时间,但在 golang 中却很快完成?

    go - docopt.go 奇怪的错误信息

    javascript - 正则表达式:查找除 "</"以外的所有斜杠

    jQuery DataTables - 通过精确匹配过滤列

    go - 学习go,想搞清楚exec包。我可以通过哪些方式改进我的代码?

    Golang 获取特定结构字段名称的字符串表示

    go - 为什么在并行处理时可以复用 Go 中的 channel ?