class RuboCop::Cop::Style::ExactRegexpMatch
string != ‘string’
# good
string !~ /Astringz/
# bad
string == ‘string’
# good
string.match?(/Astringz/)
string.match(/Astringz/)
string === /Astringz/
string =~ /Astringz/
# bad
@example
Checks for exact regexp match inside ‘Regexp` literals.
def exact_match_pattern?(parsed_regexp)
def exact_match_pattern?(parsed_regexp) tokens = parsed_regexp.map(&:token) return false unless tokens[0] == :bos && tokens[1] == :literal && tokens[2] == :eos !parsed_regexp[1].quantifier end
def new_method(node)
def new_method(node) node.method?(:!~) ? '!=' : '==' end
def on_send(node)
def on_send(node) return unless (receiver = node.receiver) return unless (regexp = exact_regexp_match(node)) return unless (parsed_regexp = parse_regexp(regexp)) return unless exact_match_pattern?(parsed_regexp) prefer = "#{receiver.source} #{new_method(node)} '#{parsed_regexp[1].text}'" add_offense(node, message: format(MSG, prefer: prefer)) do |corrector| corrector.replace(node, prefer) end end