Module: StringGlob

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

Overview

Generate a Regexp object from a glob(3) pattern

Constant Summary collapse

IGNORE_CASE =

Ignore case.

1 << 0
STAR_MATCHES_LEADING_DOT =

Leading star ‘*’ matches leading dot ‘.’.

1 << 1
STAR_MATCHES_SLASH =

Star ‘*’ matches slash ‘/’.

1 << 2
VERSION =

:nodoc:

"0.0.4"

Class Method Summary collapse

Class Method Details

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

Returns a Regex object which is the equivalent of the globbing pattern.



24
25
26
27
# File 'lib/stringglob.rb', line 24

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

Returns a regexp String object which is the equivalent of the globbing pattern.



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
93
94
95
96
97
98
# File 'lib/stringglob.rb', line 31

def regexp_string(glob, opt = 0)
  re_str = ''
  in_curlies = 0
  escaping = false
  first_byte = true
  asterisk = false
  star_matches_leading_dot = (opt & STAR_MATCHES_LEADING_DOT == 0)
  star_matches_slash = (opt & STAR_MATCHES_SLASH == 0)
  glob.scan(/./m) do |glob_c|
    if first_byte
	if star_matches_leading_dot
 re_str += '(?=[^.])' unless glob_c =~ /^[.{\[\\]$/
	end
	first_byte = false
    end
    if asterisk && glob_c != '*'
	re_str += star_matches_slash ? '[^/]*' : '.*'
	asterisk = false
    end
    if glob_c == '/'
	first_byte = true
    end
    if ('.()|+^$@%'.include?(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 ? '\\?' :
 star_matches_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 += star_matches_slash ? '[^/]*' : '.*'
  end

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

  return re_str
end