0

I'm trying to write a regex that matches anything but one word(themagicword in this example), coming from the perl/python world I would do it with a negative lookahead: ^(?!themagicword).*
How would I achieve this in golang as this doesn't seem to work in golang.

  • 1
    The stdlib regular expression engine does not support lookaheads. – Adrian Mar 01 '19 at 15:44
  • Possible duplicate of [Regex to match strings that do not start with www in golang](https://stackoverflow.com/questions/52648425/regex-to-match-strings-that-do-not-start-with-www-in-golang) – ifnotak Mar 01 '19 at 15:59
  • If you are able to use CGO, you can use one of a number of `pcre` packages [like this one](https://github.com/d4l3k/go-pcre). Just google "pcre golang" or something – Elias Van Ootegem Mar 01 '19 at 16:18
  • Shouldn't that be: `^(?!.*themagicword).*` or `^(?!themagicword$).*` ? And wouldn't it be more efficient to do `$haystack !~ /themagicword/` ? – jhnc Mar 01 '19 at 17:25
  • It sounds like you just need `if input != "themagicword" { ... }`, without regex. Or maybe `if !strings.HasPrefix(input, "themagicword") { ... }`. – Callum Watkins Mar 01 '19 at 17:37
  • See this recent answer to a similar question https://stackoverflow.com/a/54903727/1153938 – Vorsprung Mar 01 '19 at 19:41

1 Answers1

0

"matches anything but one word" is equivalent to "matches (not word)" which is equivalent to "not (matches word)". So just match the word you want to exclude and then return the inverse:

hasmagic, _ := regexp.MatchString("themagicword", "haystack")
matched := !hasmagic
jhnc
  • 11,310
  • 1
  • 9
  • 26