Class: RegexpExamples::CharGroup
- Inherits:
-
Object
- Object
- RegexpExamples::CharGroup
- Defined in:
- lib/regexp-examples/groups.rb
Instance Method Summary collapse
- #init_backslash_chars ⇒ Object
- #init_ranges ⇒ Object
-
#initialize(chars) ⇒ CharGroup
constructor
A new instance of CharGroup.
- #result ⇒ Object
Constructor Details
#initialize(chars) ⇒ CharGroup
Returns a new instance of CharGroup.
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/regexp-examples/groups.rb', line 31 def initialize(chars) @chars = chars if chars[0] == "^" @negative = true @chars = @chars[1..-1] else @negative = false end init_backslash_chars init_ranges end |
Instance Method Details
#init_backslash_chars ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/regexp-examples/groups.rb', line 66 def init_backslash_chars @chars.each_with_index do |char, i| if char == "\\" if BackslashCharMap.keys.include?(@chars[i+1]) @chars[i..i+1] = move_backslash_to_front( BackslashCharMap[@chars[i+1]] ) elsif @chars[i+1] == 'b' @chars[i..i+1] = "\b" elsif @chars[i+1] == "\\" @chars.delete_at(i+1) else @chars.delete_at(i) end end end end |
#init_ranges ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/regexp-examples/groups.rb', line 44 def init_ranges # save first and last "-" if present first = nil last = nil first = @chars.shift if @chars.first == "-" last = @chars.pop if @chars.last == "-" # Replace all instances of e.g. ["a", "-", "z"] with ["a", "b", ..., "z"] while i = @chars.index("-") # Prevent infinite loops from expanding [",", "-", "."] to itself # (Since ",".ord = 44, "-".ord = 45, ".".ord = 46) if (@chars[i-1] == ',' && @chars[i+1] == '.') first = '-' @chars.delete_at(i) else @chars[i-1..i+1] = (@chars[i-1]..@chars[i+1]).to_a end end # restore them back @chars.unshift(first) if first @chars.push(last) if last end |
#result ⇒ Object
82 83 84 85 86 |
# File 'lib/regexp-examples/groups.rb', line 82 def result (@negative ? (CharSets::Any - @chars) : @chars).map do |result| GroupResult.new(result) end end |