从字符串中提取引用部分
Extracting quoted part from string
我正在尝试使用以下代码从字符串中提取引用部分:
package main
import ("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
为什么我会收到这个错误,如何纠正?
另外,这个方法好还是其他方法更好?
这是获得所需内容的最基本方法。它可以改进为更健壮等
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)
}
}
我正在尝试使用以下代码从字符串中提取引用部分:
package main
import ("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
为什么我会收到这个错误,如何纠正?
另外,这个方法好还是其他方法更好?
这是获得所需内容的最基本方法。它可以改进为更健壮等
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)
}
}