Regex to match any .config file with a few exceptions

1.1k views Asked by At

I'm trying to get a regex working to use in an .hgignore file that will ignore various copies of .config files made during debugging.

The regex should match any path ending in .config as long as the path does not start with _config, config, or packages and as long as the file name (the characters immediately following the last slash) is not app, web, packages, or repositories (or web.release, web.debug).

The closest I seem to get is

^(?!(_config|[Cc]onfig|packages)).*\/(?!([Aa]pp|[Ww]eb|packages|repositories)\.).*config$

This will properly ignore Data/app.config, and seems to work with all other cases, but it will incorrectly match Libraries/Data/app.config. When I check this out at http://regex101.com/ it shows me that the .*\/ group is only matching through Libraries/, not Libraries/Data/ as I expected.

I tried changing it to

^(?!(_config|[Cc]onfig|packages))(.*\/)*(?!([Aa]pp|[Ww]eb|packages|repositories)\.).*config$

But then the group (.*\/)* seems to match the whole path for any .config file.

If I change the last negative lookahead to a matching group like so

^(?!(_config|[Cc]onfig|packages))(.*\/)(([Aa]pp|[Ww]eb|packages|repositories)\.).*config$

Then the (.*\/) matches Libraries/Data/, which is what I want and expected, but it appears the negative lookahead changes the matching behavior of (.*\/).

I'm not sure where to go from here? The conditions I'm trying to match or not match don't seem that complicated, but I'm not the most experienced with regexes. Maybe there is a simpler way to achieve the same thing in .hgignore?

These are examples of paths that should match and be ignored:

  • Web/smtp.config
  • Libraries/Data/connectionStrings.config

These are examples of paths that should NOT match and not be ignored

  • _config/staging/smtp.config
  • Web/web.config
  • Web/web.release.config
  • Web/Views/web.config
  • Libraries/Data/app.config
  • Libraries/Data/packages.config
  • Data/app.config
  • packages/MiniProfiler.EF6.3.0.11/lib/net40/MiniProfiler.EntityFramework6.dll.config
  • packages/repositories.config
1

There are 1 answers

1
Brian Stephens On BEST ANSWER

You were really close. Try this regex on regex101:

^(?!_?config|packages).*\/(?!(app|web|packages|repositories)\.)[^\/]*config$

I simplified it a little, but the main change was to specify no slashes in the match before the "config".

Note: I used a case-insensitive flag to simplify the regex itself.