AlexChaffee
AlexChaffee

Reputation: 8252

How to convert between a glob pattern and a regexp pattern in Ruby?

Glob patterns are similar to regexp patterns but not identical. Given a glob string, how to I convert it into the corresponding regexp string?

See Dir#glob and Perl's Text-Glob library, and Create regex from glob expression (for python).

Upvotes: 2

Views: 1878

Answers (1)

AlexChaffee
AlexChaffee

Reputation: 8252

I've written a partial implementation of this as part of the rerun gem but if anyone knows a better way, I'd love to hear about it. Here's my code (latest code and tests are up on 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

Upvotes: 2

Related Questions