Jekyll过滤内容中的正则表达式替换?

sam*_*ers 9 liquid jekyll jekyll-extensions

是否有使用正则表达式(正则表达式)过滤器替换文本的Jekyll过滤器?

我相信"内置"过滤器replace可以进行简单的字符串替换.

sam*_*ers 14

如果没有(更好的)解决方案,我会抛出一个非常简单的插件来完成这个技巧 - 将它_plugins/作为文件放入你的文件夹regex_filter.rb- 它将正则表达式作为一个字符串,作为第一个arg ,替换为第二个arg(例如{{ page.url | replace_regex: '/$', '' }}:

module Jekyll
  module RegexFilter
    def replace_regex(input, reg_str, repl_str)
      re = Regexp.new reg_str

      # This will be returned
      input.gsub re, repl_str
    end
  end
end

Liquid::Template.register_filter(Jekyll::RegexFilter)
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这在 GitHub Pages 中不起作用,因为出于安全原因它们不运行用户插件。 (3认同)
  • @CooperMaruyama如果有相同的命名常量,就不要使用魔术常量:[`Regexp :: MULTILINE`](http://ruby-doc.org/core-2.2.0/Regexp.html#constants-list )== [`4`](http://ruby-doc.org/core-2.2.0/Regexp.html#options-method) (2认同)