11

Using Mercurial, I need to ignore all files except for those in a certain directory called "keepers".

On the face of things, this seemed easy using Regex and Negative Lookahead; however, although I am able to verify my regex in Regex Buddy and other tools, in TortoiseHg, it doesn't work as expected.

Files:

  • junk\junk.txt
  • junk\text
  • keepers\test\test
  • keepers\test\test2\hi.txt
  • keepersblah.txt

Only the two files under keepers should be not be ignored.

Here is the regex I hoped would work:

^(?!keepers/).+$

Regrettably, this causes all files to be ignored. If I change it to:

^(?!keepers).+$

it works as you would expect. That is it ignores any files/folders that don't start with keepers. But I do want to ignore files that start with keepers.

Bizarrely, if I change it to this:

^(?!keepers/).+\..+$

It will properly match the folder, but it will not ignore files that are not in the keepers folder if they don't have an extension.

Any advice would be appreciated.

removing dead ImageShack link

1 Answer 1

7

The problem with your first expression is that the regex is also tested against "keepers" itself. That case can be added with an additional condition:

^(?!keepers(?:/|$))

or (less compact, but simpler to understand):

^(?!keepers/|keepers$)
3
  • I also tried ^(?!keepers\b), but that failed against "keepers.txt"
    – eswald
    Feb 11, 2010 at 19:28
  • Brilliant! Thank you so much, both worked perfectly. I've been banging my head for an hour :) Feb 11, 2010 at 19:36
  • 2
    In a look-ahead assertion there is no need for non-capturing groups, since it's not captured anyway: ^(?!keepers(/|$)).*
    – Tomalak
    Feb 11, 2010 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.