我有一些弦乐。字符串可能在方括号之间列出了项目。我想在括号内的字符串中包含一定数量的额外项目。括号可能是空的或不存在。例如:
目前,我通过以下代码(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/