Class: Uniword::FindReplace::RegexMatcher

Inherits:
Matcher
  • Object
show all
Defined in:
lib/uniword/find_replace/regex_matcher.rb

Overview

Regex matcher. Replaces every match of pattern with replacement, supporting capture-group references (\1, \2, ...) and ignore_case.

Instance Method Summary collapse

Constructor Details

#initialize(pattern:, replacement:, ignore_case: false) ⇒ RegexMatcher

Returns a new instance of RegexMatcher.

Parameters:

  • pattern (Regexp, String)

    pattern to match. String is compiled to a Regexp.

  • replacement (String)

    replacement, may reference captures

  • ignore_case (Boolean) (defaults to: false)

    force case-insensitive (only applies when pattern is a String; Regexp keeps its own flags)



14
15
16
17
# File 'lib/uniword/find_replace/regex_matcher.rb', line 14

def initialize(pattern:, replacement:, ignore_case: false)
  @pattern = compile_pattern(pattern, ignore_case)
  @replacement = replacement
end

Instance Method Details

#apply(text) ⇒ Array(String, Integer)

Parameters:

  • text (String)

Returns:

  • (Array(String, Integer))


21
22
23
24
25
26
# File 'lib/uniword/find_replace/regex_matcher.rb', line 21

def apply(text)
  matches = text.scan(@pattern).size
  return [text, 0] if matches.zero?

  [text.gsub(@pattern, @replacement), matches]
end