正则表达式忽略以字或以下划线开头的文件开头的路径

时间:2012-06-19 15:53:27

标签: ruby-on-rails ruby regex rails-admin

我一直在研究Ruby on Rails项目,该项目有贪婪的资产预编译正则表达式(在我的情况下是可取的,因为我不包括):

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

在同一个项目中,我使用的是rails_admin插件。我需要我贪婪的正则表达式来忽略rails_admin资产。我开始玩一些regex on Rubular,但无法获得最后三个示例(以 rails_admin 开头的任何)被丢弃。

如何使用忽略所有 rails_admin资产的正则表达式以及文件名以_开头,但仍然抓住其他内容的正则表达式?

1 个答案:

答案 0 :(得分:3)

%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

请注意,在Ruby正则表达式^$匹配的开头/结尾,而不是字符串,因此通常最好使用\A\z代替。


修改:这是一个允许任何路径的修改版本:

%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

根据您的编辑和评论,这里是匹配的正则表达式:

  • 任何以.css或.scss
  • 结尾的文件
  • 但如果路径以rails_admin
  • 开头,则不会
  • 而不是文件名以下划线开头

演示: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