Method: String#match!

Defined in:
lib/mini_sanity/match.rb

#match!(pattern, pos = 0) ⇒ MatchData

Like String#match, but raises an exception if the match fails.

Examples:

"[email protected]".match!(/^([^@]+)@(.+)$/)  # === MatchData
"@user".match!(/^([^@]+)@(.+)$/)             # raises exception

Parameters:

  • pattern (Regexp)

    Pattern to search for

  • pos (Integer) (defaults to: 0)

    Position in the String to search from

Returns:

  • (MatchData)

Raises:



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mini_sanity/match.rb', line 20

def match!(pattern, pos = 0)
  result = self.match(pattern, pos)

  if result.nil?
    raise MiniSanity::Error.new("String does not match pattern", {
      "String" => self.inspect,
      "Relevant portion (from position #{pos})" => (self[pos..].inspect if pos != 0),
      "Pattern" => pattern.inspect,
    })
  end

  result
end