'Is there a way to match everything except a constant string using Go.Regexp?

I have found many similar questions that do not work with the Go regex syntax.

The string that I am attempting to match against is in the form of anything/anything/somestring. With the pattern \/.*\/.*\/(.*), I will match somestring, but I am trying to match anything except strings that contain somestring.

Most answers propose using something like \/.*\/.*\/((?!somestring).*), however in golang regexp I get: ? The preceding token is not quantifiable.

For clarification: /test/test/MATCH would produce a match while /test/test/somestring would not. Is this possible with the (limited) Go regex syntax?



Solution 1:[1]

Golang intentionally leaves this feature out as there is no way to implement it in O(n) time to satisfy the constraints of a true Regular Expression according to Russ Cox:

The lack of generalized assertions, like the lack of backreferences, is not a statement on our part about regular expression style. It is a consequence of not knowing how to implement them efficiently. If you can implement them while preserving the guarantees made by the current package regexp, namely that it makes a single scan over the input and runs in O(n) time, then I would be happy to review and approve that CL. However, I have pondered how to do this for five years, off and on, and gotten nowhere.

It looks like the best way to do this is to manually check the match after as JimB mentions above.

Solution 2:[2]

There is regexp2 which implement a feature-rich RegExp engine for Go, it doesn't have constant time guarantees like the built-in regexp package, but it allows backtracking. You can use then something like (?!somestring) to solve your problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan
Solution 2 Noteworthy