我正在尝试以下代码从字符串中提取带引号的部分:package mainimport ("fmt")func main(){ var oristr = "This is a \"test string\" for testing only" var quotedstr = "" var newstr = "" var instring = false fmt.Println(oristr) for i,c := range oristr { fmt.Printf("Char number: %d; char: %c\n", i, c); if c = `"` { if instring {instring=false} else {instring=true}} if instring {quotedstr += c} else {newstr += c} } fmt.Printf("Newstr: %s; quotedstr = %s", newstr, quotedstr )}但是,我收到以下错误:# command-line-arguments./getstring.go:11:14: syntax error: c = `"` used as value./getstring.go:12:15: syntax error: unexpected newline, expecting { after if clause./getstring.go:14:4: syntax error: unexpected else, expecting }./getstring.go:15:3: syntax error: non-declaration statement outside function body为什么我会收到此错误以及如何纠正此错误?另外,这种方法可以吗?还是其他方法可能更好?
1 回答
一只甜甜圈
TA贡献1836条经验 获得超5个赞
这是获得你想要的东西的最基本的方法。它可以改进得更加健壮等等。
package main
import (
"fmt"
"regexp"
)
func main() {
var oristr = "This is a \"test string\" for containing multiple \"test strings\" and another \"one\" here"
re := regexp.MustCompile(`"[^"]+"`)
newStrs := re.FindAllString(oristr, -1)
for _, s := range newStrs {
fmt.Println(s)
}
}
- 1 回答
- 0 关注
- 126 浏览
添加回答
举报
0/150
提交
取消