Negative look-ahead in Go regular expressions

前端 未结 3 1697
日久生厌
日久生厌 2020-12-03 09:54

I\'m trying to use negative look-aheads in Go.

The following regular expression: BBB(((?!BBB).)*)EEE

http://rubular.com/r/Zw1vopp1MF

Howeve

3条回答
  •  佛祖请我去吃肉
    2020-12-03 10:10

    Negative lookahead isn't supported for technical reasons, specifically because it conflicts with the O(n)-time guarantees of the library. See the golang-nuts group discussion about this, as well as the Caveats section in Regular Expression Matching in the Wild.

    You can express the regular expression you've described without negative lookahead:

    BBB([^B]|B[^B]|BB[^B])*EEE
    

    Here's an example to demonstrate:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        re := regexp.MustCompile(`BBB([^B]|B[^B]|BB[^B])*EEE`)
        fmt.Printf("%#v\n", re.FindAllString("BBB EEE BBB..BBB...EEE", -1))
    }
    

提交回复
热议问题