duanfu9523 2019-08-11 13:48
浏览 72
已采纳

从字符串中提取引用的部分[关闭]

I am trying following code to extract quoted part from a 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
", 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 )
}

However, I am getting following error:

# 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

Why I am getting this error and how can this be corrected?

Also, is this approach all right or some other approach may be better?

  • 写回答

1条回答 默认 最新

  • dpda53918 2019-08-11 14:12
    关注

    This is the most basic way of getting what you want. It could be improved to be more robust etc.

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nrf52810-c三个a 程序
  • ¥15 lego-loam跑出来的roll误差很大
  • ¥50 求一个半透明没有锯齿的圆角窗体的实现例子
  • ¥15 STM32cubeMX里的FreeRTOS无法释放内存
  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对