如何在Ruby中的glob模式和regexp模式之间转换? [英] How to convert between a glob pattern and a regexp pattern in Ruby?

查看:61
本文介绍了如何在Ruby中的glob模式和regexp模式之间转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Glob模式与正则表达式模式相似,但不相同.给定一个glob字符串,如何将其转换为相应的regexp字符串?

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

请参见 Dir#glob 和Perl的 Text-Glob 库和从glob表达式创建正则表达式(适用于python).

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

推荐答案

作为代码测试在github上进行.

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

这篇关于如何在Ruby中的glob模式和regexp模式之间转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆