2

我一直在研究一个 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资产。我开始在 Rubular 上使用一些正则表达式,但无法丢弃最后三个示例(以 开头的任何内容rails_admin)。

如何使用忽略所有rails_admin 资产和文件名以 开头_但仍获取其他所有内容的正则表达式?

4

1 回答 1

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 正则表达式中^$匹配行的开始/结束而不是字符串,因此通常最好使用\Aand\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
于 2012-06-19T15:57:41.880 回答