douhoujun9304 2015-06-04 00:44
浏览 43
已采纳

拆分字符串时,如何在输出中包括运算符?

Yesterday I asked this question about splitting a string in python. I've since decided to do this project in Go instead. I have the following:

input := "house-width + 3 - y ^ (5 * house length)"
s := regexp.MustCompile(" ([+-/*^]) ").Split(input, -1)
log.Println(s)  //  [house-width 3 y (5 house length)]

How do I include the operators in this output? e.g. I'd like the following output:

['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)']

EDIT: To clarify I am splitting on the space-separated operators and not just the operator. The operator must have a space on both ends to differentiate it from a dash/hyphen. Please refer to my original python question I linked to for clarification if needed.

  • 写回答

3条回答 默认 最新

  • dshnx48866 2015-06-04 07:29
    关注

    You can get the operands of your expression using regexp.Split() (just as you did) and you can get the operators (the separators) using regexp.FindAllString().

    By doing this you will have 2 separate []string slices, you can merge these 2 slices if you want the result in one []string slice.

    input := "house-width + 3 - y ^ (5 * house length)"
    
    r := regexp.MustCompile(`\s([+\-/*^])\s`)
    
    s1 := r.Split(input, -1)
    s2 := r.FindAllString(input, -1)
    
    fmt.Printf("%q
    ", s1)
    fmt.Printf("%q
    ", s2)
    
    all := make([]string, len(s1)+len(s2))
    for i := range s1 {
        all[i*2] = s1[i]
        if i < len(s2) {
            all[i*2+1] = s2[i]
        }
    }
    fmt.Printf("%q
    ", all)
    

    Output (try it on the Go Playground):

    ["house-width" "3" "y" "(5" "house length)"]
    [" + " " - " " ^ " " * "]
    ["house-width" " + " "3" " - " "y" " ^ " "(5" " * " "house length)"]
    

    Note:

    If you want to trim the spaces from the operators, you can use the strings.TrimSpace() function for that:

    for i, v := range s2 {
        all[i*2+1] = strings.TrimSpace(v)
    }
    fmt.Printf("%q
    ", all)
    

    Output:

    ["house-width" "+" "3" "-" "y" "^" "(5" "*" "house length)"]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真