Class: TreRegex::Regex

Inherits:
Object
  • Object
show all
Defined in:
lib/tre_regex.rb

Overview

User-Facing Ruby Class

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pattern, ignore_case: false) ⇒ Regex

Returns a new instance of Regex.

Raises:



81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/tre_regex.rb', line 81

def initialize(pattern, ignore_case: false)
  @pattern = pattern
  # Allocate a safe 256-byte buffer in C memory for the regex_t struc
  @preg = FFI::MemoryPointer.new(:char, 256)

  flags = Native::REG_EXTENDED
  flags |= Native::REG_ICASE if ignore_case

  res = Native.tre_regcomp(@preg, pattern, flags)
  raise TreRegex::Error, "Failed to compile regex pattern: #{pattern}" if res != 0

  # Garbage Collection Hook: Tell Ruby to free the C memory when this object is destroyed
  ObjectSpace.define_finalizer(self, self.class.finalize(@preg))
end

Instance Attribute Details

#patternObject (readonly)

Returns the value of attribute pattern.



79
80
81
# File 'lib/tre_regex.rb', line 79

def pattern
  @pattern
end

Class Method Details

.finalize(preg_ptr) ⇒ Object

The GC finalizer proc



97
98
99
100
101
102
# File 'lib/tre_regex.rb', line 97

def self.finalize(preg_ptr)
  proc do
    Native.tre_regfree(preg_ptr)
    preg_ptr.free
  end
end

Instance Method Details

#exec(text, options = {}) ⇒ Object



104
105
106
107
108
109
110
111
# File 'lib/tre_regex.rb', line 104

def exec(text, options = {})
  params = build_params(options)
  pmatch = FFI::MemoryPointer.new(Native::RegMatch)
  match_data = prepare_match_data(pmatch)

  res = Native.tre_regaexec(@preg, text, match_data, params, 0)
  res.zero? ? parse_result(text, match_data, pmatch) : nil
end

#match_all(text, options = {}) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/tre_regex.rb', line 117

def match_all(text, options = {})
  return enum_for(:match_all, text, options) unless block_given?

  offset = 0
  while offset <= text.length
    result = exec(text[offset..] || '', options)
    break unless result

    result[:index] += offset
    result[:end_index] += offset
    yield result

    advance = (result[:end_index] - result[:index]).clamp(1, Float::INFINITY)
    offset = result[:index] + advance
  end
end

#test?(text, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


113
114
115
# File 'lib/tre_regex.rb', line 113

def test?(text, options = {})
  !exec(text, options).nil?
end