photools.com Community

IMatch Discussion Boards => General Discussion and Questions => Topic started by: axel.hennig on September 06, 2019, 11:22:33 PM

Title: Negation in RegEx
Post by: axel.hennig on September 06, 2019, 11:22:33 PM
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 (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?
Title: Re: Negation in RegEx
Post by: thrinn on September 07, 2019, 10:07:35 AM
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 (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).
Title: Re: Negation in RegEx
Post by: axel.hennig on September 07, 2019, 04:06:56 PM
Thanks Thorsten,

works as expected. Thank you very much.

Nevertheless, I still would like to know why my first try did not work...
Title: Re: Negation in RegEx
Post by: thrinn on September 07, 2019, 04:45:39 PM
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/ (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
Title: Re: Negation in RegEx
Post by: axel.hennig on September 07, 2019, 10:07:00 PM
Thanks again, works perfect.