How to simulate negative lookbehind in Go

后端 未结 2 1032
心在旅途
心在旅途 2020-12-20 15:23

I\'m trying to write a regex that can extract a command, here\'s what I\'ve got so far using a negative lookbehind assertion:



        
2条回答
  •  执念已碎
    2020-12-20 15:49

    Since in your negated lookbehind, you are only using a simple character set; you can replace it with a negated character-set:

    \b[^@#/]\w.*
    

    If the are allowed at the start of the string, then use the ^ anchor:

    (?:^|[^@#\/])\b\w.*
    

    Based on the samples in Go playground link in your question, I think you're looking to filter out all words beginning with a character from [#@/]. You can use a filter function:

    func Filter(vs []string, f func(string) bool) []string {
        vsf := make([]string, 0)
        for _, v := range vs {
            if f(v) {
                vsf = append(vsf, v)
            }
        }
        return vsf
    }
    

    and a Process function, which makes use of the filter above:

    func Process(inp string) string {
        t := strings.Split(inp, " ")
        t = Filter(t, func(x string) bool {
            return strings.Index(x, "#") != 0 &&
                strings.Index(x, "@") != 0 &&
                strings.Index(x, "/") != 0
        })
        return strings.Join(t, " ")
    }
    

    It can be seen in action on playground at http://play.golang.org/p/ntJRNxJTxo

提交回复
热议问题