parkr
parkr

Reputation: 833

Regex to ignore paths starting with word or files starting with underscore

I have been working on a Ruby on Rails project which has greedy asset precompile regex (which is desirable in my case, because I'm not including ):

# in config/application.rb
# this excludes all files which start with an '_' character (sass)
config.assets.precompile << /(?<!rails_admin)(^[^_\/]|\/[^_])([^\/])*.s?css$/

In this same project, I am using the rails_admin plugin. I need my greedy regex to ignore rails_admin assets. I started to play around with some regex on Rubular but couldn't get the last three examples (anything that starts with rails_admin) to be discarded.

How can I use regex that ignores all rails_admin assets and those whose file names begin with an _, but still grabs everything else?

Upvotes: 2

Views: 1164

Answers (1)

Phrogz
Phrogz

Reputation: 303441

%r{               # Use %r{} instead of /…/ so we don't have to escape slashes
  \A              # Make sure we start at the front of the string
  (?!rails_admin) # NOW ensure we can't see rails_admin from here 
  ([^_/]|/[^_])   # (I have no idea what your logic is here)
  ([^/]*)         # the file name
  \.s?css         # the extension
  \z              # Finish with the very end of the string
}x                # Extended mode allows us to put spaces and comments in here

Note that in Ruby regex ^ and $ match the start/end of a line, not the string, so it's generally better to use \A and \z instead.


Edit: Here's a modified version that allows any paths:

%r{               # Use %r{} instead of /…/ so we don't have to escape slashes
  \A              # Make sure we start at the front of the string
  (?!rails_admin) # NOW ensure we can't see rails_admin from here 
  (.+/)?          # Anything up to and including a slash, optionally
  ([^/]*)         # the file name
  \.s?css         # the extension
  \z              # Finish with the very end of the string
}x                # Extended mode allows us to put spaces and comments in here

Based on your edits and comments, here's a regex that matches:

  • any file that ends with .css or .scss
  • but not if the path starts with rails_admin
  • and not if the filename starts with an underscore

Demo: http://rubular.com/r/Y3Mn3c9Ioc

%r{               # Use %r{} instead of /…/ so we don't have to escape slashes
  \A              # Make sure we start at the front of the string
  (?!rails_admin) # NOW ensure we can't see rails_admin from here 
  (?:.+/)?        # Anything up to and including a slash, optionally (not saved)
  (?!_)           # Make sure that we can't see an underscore immediately ahead
  ([^/]*)         # the file name, captured
  \.s?css         # the extension
  \z              # Finish with the very end of the string
}x                # Extended mode allows us to put spaces and comments in here

Upvotes: 3

Related Questions