Module: StringGlob

Defined in:
lib/stringglob.rb,
lib/stringglob/version.rb

Constant Summary collapse

IGNORE_CASE =
1 << 0
NO_STRICT_LEADING_DOT =
1 << 1
NO_STRICT_WILDCARD_SLASH =
1 << 2
VERSION =
"0.0.1"

Class Method Summary collapse

Class Method Details

.regexp(glob, opt = 0, code = nil) ⇒ Object



18
19
20
21
# File 'lib/stringglob.rb', line 18

def regexp(glob, opt = 0, code = nil)
  re = regexp_string(glob, opt)
  return Regexp.new("\\A#{re}\\z", nil, code)
end

.regexp_string(glob, opt = 0) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/stringglob.rb', line 24

def regexp_string(glob, opt = 0)
  re_str = ''
  in_curlies = 0
  escaping = false
  first_byte = true
  asterisk = false
  strict_leading_dot = (opt & NO_STRICT_LEADING_DOT == 0)
  strict_wildcard_slash = (opt & NO_STRICT_WILDCARD_SLASH == 0)
  glob.scan(/./m) do |glob_c|
    if first_byte
	if strict_leading_dot
 re_str += '(?=[^\.])' unless glob_c == '.'
	end
	first_byte = false
    end
    if asterisk && glob_c != '*'
	re_str += strict_wildcard_slash ? '[^/]*' : '.*'
	asterisk = false
    end
    if glob_c == '/'
	first_byte = true
    end
    if (glob_c == '.' || glob_c == '(' || glob_c == ')' || glob_c == '|' ||
 glob_c == '+' || glob_c == '^' || glob_c == '$' || glob_c == '@' || glob_c == '%' )
	re_str += '\\' + glob_c
    elsif glob_c == '*'
	if escaping
 re_str += '\\*'
	elsif asterisk
 re_str += '.*'
 asterisk = false
	else
 asterisk = true
	end
    elsif glob_c == '?'
	re_str += escaping ? '\\?' :
 strict_wildcard_slash ? '[^/]' : '.'
    elsif glob_c == '{'
	re_str += escaping ? '\\{' : '('
	in_curlies += 1 unless escaping
    elsif glob_c == '}' && in_curlies > 0
	re_str += escaping ? '}' : ')'
	in_curlies -= 1 unless escaping
    elsif glob_c == ',' && in_curlies > 0
	re_str += escaping ? ',' : '|'
    elsif glob_c == '\\'
	if escaping
 re_str += '\\\\'
 escaping = false
	else
 escaping = true
	end
	next
    else
	## Suppress warning: re_str has `}' without escape
	re_str += '\\' if glob_c == '}'
	re_str += glob_c
	escaping = false
    end
    escaping = false
  end
  if asterisk
    re_str += strict_wildcard_slash ? '[^/]*' : '.*'
  end

  re_str = "(?i:#{re_str})" if (opt & IGNORE_CASE != 0)

  return re_str
end