Momchil Milev
Momchil Milev

Reputation: 38

skipping comments with regex

this has been asked so many times - yet I don't get why the following negative look-behind still matches after the comment character ";" ?!

   (?<!;).+mylib.*

Regular expression visualization

Debuggex Demo

TEST-TEXT:

;   /home/mylib/blabla/laydef1.rul (matches wrongly!?)

/home/mylib/blabla/laydef2.rul (matches as it should)

P.S. RegEx class is PCRE

Upvotes: 1

Views: 35

Answers (1)

anubhava
anubhava

Reputation: 785128

Since PCRE doesn't support variable length lookbehind you can use this regex construct:

/^\h*(?:;.*(*SKIP)(*F)|.*mylib.*)/m

RegEx Demo

Your regex: (?<!;).+mylib.* fails because .+ matches everything from ; tomylib`

  • (*FAIL) behaves like a failing negative assertion and is a synonym for (?!)
  • (*SKIP) defines a point beyond which the regex engine is not allowed to backtrack when the subpattern fails later
  • (*SKIP)(*FAIL) together provide a nice alternative of restriction that you cannot have a variable length lookbehind in above regex.

Upvotes: 1

Related Questions