1

When I try this regex in Golang I'm getting a regex parsing error.

panic: regexp: Compile(.+?(?=someText)): error parsing regexp: invalid or unsupported Perl syntax: (?=

regexp.MustCompile(`.+?(?=someText)`)

This is probably something to do with lookarounds, but I'm not sure about what the solution is as I don't have much experience with regex.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
clattenburg cake
  • 1,096
  • 3
  • 19
  • 40
  • The `(?=pattern)` is a legitimate [lookahead](https://perldoc.perl.org/perlretut#Looking-ahead-and-looking-behind) assertion -- in Perl, what you tagged (for some reason?). The whole pattern would be a way to get the engine to the place just before `someText` (having "consumed" whatever precedes that zero-width "place"). I don't know how it goes in Go though ... but it appears that it just isn't supported? Perhaps syntax for it is different? – zdim Dec 17 '20 at 05:24
  • 1
    At [this doc](https://github.com/google/re2/wiki/Syntax) it says 'not supported' for that ... and see [this page](https://stackoverflow.com/q/30305542/4653379), which practically answers the question. One of the answers also offers an alternative – zdim Dec 17 '20 at 05:35
  • It's basically trying to tell you "you thought Go supported this Perl regex extension, but this is not Perl". – tripleee Dec 17 '20 at 05:46
  • The perl tag is for the perl *programming language*, not regular expressions in other languages. – Shawn Dec 17 '20 at 11:09

1 Answers1

2

Judging by the first question mark, it seems like you're trying to get the substring before the first occurrence of someText. If that is in fact the case, you could use this as an alternative:

package main
import "strings"

func main() {
   s := "March someText April someText"
   n := strings.Index(s, "someText")
   s = s[:n]
   println(s == "March ")
}

https://golang.org/pkg/strings#Index

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Zombo
  • 1
  • 62
  • 391
  • 407