Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

go

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?

like image 924
Ryan Avatar asked Feb 28 '17 17:02

Ryan


People also ask

How do you match everything except with regex?

How do you ignore something in regex? To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

How do you check if a regex matches a string?

If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() .

Does regex only work on strings?

So, yes, regular expressions really only apply to strings. If you want a more complicated FSM, then it's possible to write one, but not using your local regex engine.


1 Answers

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.

like image 84
Ryan Avatar answered Oct 07 '22 22:10

Ryan