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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效