Negation in RegEx

Started by axel.hennig, September 06, 2019, 11:22:33 PM

Previous topic - Next topic

axel.hennig

Hi,

I tried to use filter in File.Categories but it is not working as expected (tested in the VarToy-app). I want to return all categories exept the ones below @Keywords. I tried

{File.Categories|filter:(?!^@Keywords)}

which should work as stated in https://stackoverflow.com/questions/6361312/negative-regex-for-perl-string-pattern-match, but it does not.

{File.Categories|filter:(?=^@Keywords)}

returns everything as expected.

Can anybody help me? Ho do I negate a search-string?

thrinn

I am not very familiar with these lookahead operators. But a (maybe simpler) approach would be to grab the categories tha you want instead of excluding those you do not want.
For example, this expression returns categories starting with a "word" character. Apparently, these do not include the @ character.
{File.Categories|filter:^[\w].*}
This will return all categories starting with a letter, number, underscore (see https://www.regular-expressions.info/shorthand.html). Assuming all your categories start with one of these, you should get your own categories without @Keywords (and @Builder).
Thorsten
Win 10 / 64, IMatch 2018, IMA

axel.hennig

Thanks Thorsten,

works as expected. Thank you very much.

Nevertheless, I still would like to know why my first try did not work...

thrinn

#3
Just tried

{File.Categories|filter:^(?!@Keywords)}

And this seems to work!

My explanation (on aftersight), taking into account the definition given on https://regex101.com/ (thanks again, Jingo, for providing this link!):
(?!...)
Starting at the current position in the expression, ensures that the given pattern will not match. Does not consume characters.

So maybe the ^ clashes somehow with the "current position" in your expression. Putting ^ outside of the negative lookahead would then mean: If the current position is "start of expression", check that it is not followed by @Keywords. This makes sense, somehow at least.

But I have no clue how RegExp engines work internally, so I might be completely wrong.  :o
Thorsten
Win 10 / 64, IMatch 2018, IMA

axel.hennig

Thanks again, works perfect.