Skip to content
instance method

StringScanner#match?

(::Regexp) -> ::Integer?
match?(pattern) → updated_position or nil

Attempts to match the given pattern at the beginning of the target substring; does not modify the positions.

If the match succeeds:

  • Sets match values.

  • Returns the size in bytes of the matched substring.

Example
scanner = StringScanner.new('foobarbaz')
scanner.pos = 3
scanner.match?(/bar/) => 3
put_match_values(scanner)
# Basic match values:
#   matched?:       true
#   matched_size:   3
#   pre_match:      "foo"
#   matched  :      "bar"
#   post_match:     "baz"
# Captured match values:
#   size:           1
#   captures:       []
#   named_captures: {}
#   values_at:      ["bar", nil]
#   []:
#     [0]:          "bar"
#     [1]:          nil
put_situation(scanner)
# Situation:
#   pos:       3
#   charpos:   3
#   rest:      "barbaz"
#   rest_size: 6

If the match fails:

  • Clears match values.

  • Returns nil.

  • Does not increment positions.

Example
scanner.match?(/nope/)         # => nil
match_values_cleared?(scanner) # => true
See also #inspect #matched #initialize_copy #matched? also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0