Negative look-ahead in Go regular expressions

K2xL picture K2xL · Nov 6, 2014 · Viewed 23.3k times · Source

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

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

http://rubular.com/r/Zw1vopp1MF

However, in Go I get:

error parsing regexp: invalid or unsupported Perl syntax: `(?!`

Are there any alternatives?

Answer

dyoo picture dyoo · Nov 7, 2014

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