Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用正则表达式将字符串包含到另一个字符串中_Regex_Go - Fatal编程技术网

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

Regex 使用正则表达式将字符串包含到另一个字符串中,regex,go,Regex,Go,我有一些弦。字符串可能在方括号中列出了项。我想在带括号的字符串中包含固定数量的额外项。括号可能为空或不存在。例如: string1-->string1#未添加任何内容 string2[]->string2[extra1=“1”,extra2=“2”]#添加了两项 string3[item=“1”]->string3[item=“1”,extra1=“1”,extra2=“2”]#添加了两项 目前,我通过以下代码(Golang)实现了这一点: 但在输出中,在空括号的情况下,我还得到了一个不需要

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

  • string1-->string1#未添加任何内容
  • string2[]->string2[extra1=“1”,extra2=“2”]#添加了两项
  • string3[item=“1”]->string3[item=“1”,extra1=“1”,extra2=“2”]#添加了两项
目前,我通过以下代码(Golang)实现了这一点:

但在输出中,在空括号的情况下,我还得到了一个不需要的逗号“,”,最后:

test
test[item1="a",item2="b",]
test[item1="a",item2="b",item1="1"]
如果括号为空,是否可以避免粘贴逗号

当然,可以再次解析字符串并修剪逗号,但这似乎不太理想

您可以有两个正则表达式,其中一个匹配空[],另一个匹配空[] 匹配文本在[]内的字符串。下面是经过测试的代码-

第二种方法是在替换字符串后回顾它。如果 最后两个字符是,],您可以使用子字符串till和add]。我 我猜你已经知道这种方法了

test
test[item1="a",item2="b",]
test[item1="a",item2="b",item1="1"]
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)
    }
}