Class: PCRE2::Regexp

Inherits:
Object
  • Object
show all
Includes:
StringUtils
Defined in:
lib/pcre2/regexp.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from StringUtils

#scan, #split

Constructor Details

#initialize(pattern, *options) ⇒ Regexp

Accepts a String, Regexp or another PCRE2::Regexp



8
9
10
11
12
13
14
15
16
17
# File 'lib/pcre2/regexp.rb', line 8

def initialize(pattern, *options)
  case pattern
  when ::Regexp, PCRE2::Regexp
    @source = pattern.source
  else
    @source = pattern
  end

  @pattern_ptr = Lib.compile_pattern(source, options)
end

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



3
4
5
# File 'lib/pcre2/regexp.rb', line 3

def source
  @source
end

Instance Method Details

#jit!Object

Compiles the Regexp into a JIT optimised version. Returns whether it was successful



20
21
22
23
24
# File 'lib/pcre2/regexp.rb', line 20

def jit!
  options = PCRE2_JIT_COMPLETE | PCRE2_JIT_PARTIAL_SOFT | PCRE2_JIT_PARTIAL_HARD

  Lib.pcre2_jit_compile_8(pattern_ptr, options) == 0
end

#match(str, pos = nil) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pcre2/regexp.rb', line 26

def match(str, pos = nil)
  result_count, match_data_ptr = Lib.match(@pattern_ptr, str, position: pos)

  if result_count == 0
    nil
  else
    pairs = PCRE2::Lib.get_ovector_pairs(match_data_ptr, result_count)

    MatchData.new(self, str, pairs)
  end
end

#matches(str, pos = nil, &block) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/pcre2/regexp.rb', line 38

def matches(str, pos = nil, &block)
  return enum_for(:matches, str, pos) if !block_given?

  pos ||= 0
  while pos < str.length
    matchdata = self.match(str, pos)

    if matchdata
      yield matchdata

      beginning, ending = matchdata.offset(0)

      if pos == ending # Manually increment position if no change to avoid infinite loops
        pos += 1
      else
        pos = ending
      end
    else
      return
    end
  end
end

#named_capturesObject



61
62
63
# File 'lib/pcre2/regexp.rb', line 61

def named_captures
  @named_captures ||= Lib.named_captures(pattern_ptr)
end

#namesObject



65
66
67
# File 'lib/pcre2/regexp.rb', line 65

def names
  named_captures.keys
end