如何在Ruby中的glob模式和regexp模式之间进行转换?

时间:2012-06-30 19:10:28

标签: ruby regex glob

Glob模式与regexp模式类似,但不完全相同。给定一个glob字符串,如何将其转换为相应的regexp字符串?

请参阅Dir#glob和Perl的Text-Glob库,以及Create regex from glob expression(对于python)。

1 个答案:

答案 0 :(得分:2)

我作为rerun宝石的一部分写了部分实现,但如果有人知道更好的方法,我很乐意听到它。这是我的代码(最新的codetests在github上。)

class Glob
  NO_LEADING_DOT = '(?=[^\.])'   # todo

  def initialize glob_string
    @glob_string = glob_string
  end

  def to_regexp_string
    chars = @glob_string.split('')
    in_curlies = 0;
    escaping = false;
    chars.map do |char|
      if escaping
        escaping = false
        char
      else
        case char
          when '*'
            ".*"
          when "?"
            "."
          when "."
            "\\."

          when "{"
            in_curlies += 1
            "("
          when "}"
            if in_curlies > 0
              in_curlies -= 1
              ")"
            else
              char
            end
          when ","
            if in_curlies > 0
              "|"
            else
              char
            end
          when "\\"
            escaping = true
            "\\"

          else
            char

        end
      end
    end.join
  end
end