Regex::MatchData - Crystal 1.7.1

# struct Regex::MatchData

- Regex::MatchData
- Struct
- Value
- Object

##
Overview

`Regex::MatchData` is the type of the special variable `$~`, and is the type returned by `Regex#match` and `String#match`. It encapsulates all the results of a regular expression match.

    if md = "Crystal".match(/[p-s]/)
      md.string # => "Crystal"
      md[0]     # => "r"
      md[1]?    # => nil
    end

Many `Regex::MatchData` methods deal with capture groups, and accept an integer argument to select the desired capture group. Capture groups are numbered starting from `1`, so that `0` can be used to refer to the entire regular expression without needing to capture it explicitly.

##
Included Modules

- Regex::PCRE::MatchData

##
Defined in:

regex/match_data.cr

##
Instance Method Summary

- #==(other : Regex::MatchData)
- #[](start : Int, count : Int) : Array(String)

  Returns count or less (if there aren't enough) matches starting at the given start index.

- #[](n : Int) : String

  Returns the match of the nth capture group, or raises an `IndexError` if there is no nth capture group.

- #[](group_name : String) : String

  Returns the match of the capture group named by group_name, or raises an `KeyError` if there is no such named capture group.

- #[](range : Range) : Array(String)

  Returns all matches that are within the given range.

- #[]?(start : Int, count : Int) : Array(String) | Nil

  Like `#[](Int, Int)` but returns `nil` if the start index is out of range.

- #[]?(n : Int) : String | Nil

  Returns the match of the nth capture group, or `nil` if there isn't an nth capture group.

- #[]?(group_name : String) : String | Nil

  Returns the match of the capture group named by group_name, or `nil` if there is no such named capture group.

- #[]?(range : Range) : Array(String) | Nil

  Like `#[](Range)`, but returns `nil` if the range's start is out of range.

- #begin(n = 0) : Int32

  Returns the position of the first character of the nth match.

- #byte_begin(n = 0) : Int32

  Returns the position of the first byte of the nth match.

- #byte_end(n = 0) : Int32

  Returns the position of the next byte after the match.

- #captures : Array(String | Nil)

  Returns an array of unnamed capture groups.

- #clone
- #dup

  Returns a shallow copy of this object.

- #end(n = 0) : Int32

  Returns the position of the next character after the match.

- #group_size : Int32

  Returns the number of capture groups, including named capture groups.

- #hash(hasher)

  See `Object#hash(hasher)`

- #inspect(io : IO) : Nil

  Appends this struct's name and instance variables names and values to the given IO.

- #named_captures : Hash(String, String | Nil)

  Returns a hash of named capture groups.

- #post_match : String

  Returns the part of the original string after the match.

- #pre_match : String

  Returns the part of the original string before the match.

- #pretty_print(pp) : Nil
- #regex : Regex

  Returns the original regular expression.

- #size : Int32

  Returns the number of elements in this match object.

- #string : String

  Returns the original string.

- #to_a : Array(String | Nil)

  Convert this match data into an array.

- #to_h : Hash(Int32 | String, String | Nil)

  Convert this match data into a hash.

- #to_s(io : IO) : Nil

  Same as `#inspect(io)`.

### Instance methods inherited from struct `Struct`

==(other) : Bool ==, hash(hasher) hash, inspect(io : IO) : Nil inspect, pretty_print(pp) : Nil pretty_print, to_s(io : IO) : Nil to_s

### Instance methods inherited from struct `Value`

==(other : JSON::Any)
==(other : YAML::Any)
==(other) ==, dup dup

### Instance methods inherited from class `Object`

! : Bool !, !=(other) !=, !~(other) !~, ==(other) ==, ===(other : JSON::Any)
===(other : YAML::Any)
===(other) ===, =~(other) =~, as(type : Class) as, as?(type : Class) as?, class class, dup dup, hash(hasher)
hash hash, in?(collection : Object) : Bool
in?(*values : Object) : Bool in?, inspect(io : IO) : Nil
inspect : String inspect, is_a?(type : Class) : Bool is_a?, itself itself, nil? : Bool nil?, not_nil!(message = nil) not_nil!, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, responds_to?(name : Symbol) : Bool responds_to?, tap(&) tap, to_json(io : IO) : Nil
to_json : String to_json, to_pretty_json(indent : String = " ") : String
to_pretty_json(io : IO, indent : String = " ") : Nil to_pretty_json, to_s(io : IO) : Nil
to_s : String to_s, to_yaml(io : IO) : Nil
to_yaml : String to_yaml, try(&) try, unsafe_as(type : T.class) forall T unsafe_as

### Class methods inherited from class `Object`

from_json(string_or_io, root : String)
from_json(string_or_io) from_json, from_yaml(string_or_io : String | IO) from_yaml

##
Instance Method Detail

def ==(other : Regex::MatchData) #
def [](start : Int, count : Int) : Array(String) #

Returns count or less (if there aren't enough) matches starting at the given start index.

def [](n : Int) : String #

Returns the match of the nth capture group, or raises an `IndexError` if there is no nth capture group.

    "Crystal".match(/r(ys)/).not_nil![1] # => "ys"
    "Crystal".match(/r(ys)/).not_nil![2] # raises IndexError

def [](group_name : String) : String #

Returns the match of the capture group named by group_name, or raises an `KeyError` if there is no such named capture group.

    "Crystal".match(/r(?<ok>ys)/).not_nil!["ok"] # => "ys"
    "Crystal".match(/r(?<ok>ys)/).not_nil!["ng"] # raises KeyError

When there are capture groups having same name, it returns the last matched capture group.

    "Crystal".match(/(?<ok>Cr).*(?<ok>al)/).not_nil!["ok"] # => "al"

def [](range : Range) : Array(String) #

Returns all matches that are within the given range.

def []?(start : Int, count : Int) : Array(String) | Nil #

Like `#[](Int, Int)` but returns `nil` if the start index is out of range.

def []?(n : Int) : String | Nil #

Returns the match of the nth capture group, or `nil` if there isn't an nth capture group.

When n is `0`, returns the match for the entire `Regex`.

    "Crystal".match(/r(ys)/).not_nil![0]? # => "rys"
    "Crystal".match(/r(ys)/).not_nil![1]? # => "ys"
    "Crystal".match(/r(ys)/).not_nil![2]? # => nil

def []?(group_name : String) : String | Nil #

Returns the match of the capture group named by group_name, or `nil` if there is no such named capture group.

    "Crystal".match(/r(?<ok>ys)/).not_nil!["ok"]? # => "ys"
    "Crystal".match(/r(?<ok>ys)/).not_nil!["ng"]? # => nil

When there are capture groups having same name, it returns the last matched capture group.

    "Crystal".match(/(?<ok>Cr).*(?<ok>al)/).not_nil!["ok"]? # => "al"

def []?(range : Range) : Array(String) | Nil #

Like `#[](Range)`, but returns `nil` if the range's start is out of range.

def begin(n = 0) : Int32 #

Returns the position of the first character of the nth match.

When n is `0` or not given, uses the match of the entire `Regex`. Otherwise, uses the match of the nth capture group.

Raises `IndexError` if the index is out of range or the respective subpattern is unused.

    "Crystal".match(/r/).not_nil!.begin(0)     # => 1
    "Crystal".match(/r(ys)/).not_nil!.begin(1) # => 2
    "クリスタル".match(/リ(ス)/).not_nil!.begin(0)    # => 1
    "Crystal".match(/r/).not_nil!.begin(1)     # IndexError: Invalid capture group index: 1
    "Crystal".match(/r(x)?/).not_nil!.begin(1) # IndexError: Capture group 1 was not matched

def byte_begin(n = 0) : Int32 #

Returns the position of the first byte of the nth match.

When n is `0` or not given, uses the match of the entire `Regex`. Otherwise, uses the match of the nth capture group.

Raises `IndexError` if the index is out of range or the respective subpattern is unused.

    "Crystal".match(/r/).not_nil!.byte_begin(0)     # => 1
    "Crystal".match(/r(ys)/).not_nil!.byte_begin(1) # => 2
    "クリスタル".match(/リ(ス)/).not_nil!.byte_begin(0)    # => 3
    "Crystal".match(/r/).not_nil!.byte_begin(1)     # IndexError: Invalid capture group index: 1
    "Crystal".match(/r(x)?/).not_nil!.byte_begin(1) # IndexError: Capture group 1 was not matched

def byte_end(n = 0) : Int32 #

Returns the position of the next byte after the match.

When n is `0` or not given, uses the match of the entire `Regex`. Otherwise, uses the match of the nth capture group.

Raises `IndexError` if the index is out of range or the respective subpattern is unused.

    "Crystal".match(/r/).not_nil!.byte_end(0)     # => 2
    "Crystal".match(/r(ys)/).not_nil!.byte_end(1) # => 4
    "クリスタル".match(/リ(ス)/).not_nil!.byte_end(0)    # => 9
    "Crystal".match(/r/).not_nil!.byte_end(1)     # IndexError: Invalid capture group index: 1
    "Crystal".match(/r(x)?/).not_nil!.byte_end(1) # IndexError: Capture group 1 was not matched

def captures : Array(String | Nil) #

Returns an array of unnamed capture groups.

It is a difference from `#to_a` that the result array does not contain the match for the entire `Regex` (`self[0]`).

    match = "Crystal".match(/(Cr)(?<name1>y)(st)(?<name2>al)/).not_nil!
    match.captures # => ["Cr", "st"]

    # When this regex has an optional group, result array may contain
    # a `nil` if this group is not matched.
    match = "Crystal".match(/(Cr)(stal)?/).not_nil!
    match.captures # => ["Cr", nil]

def clone #
def dup #
Description copied from struct Value

Returns a shallow copy of this object.

Because `Value` is a value type, this method returns `self`, which already involves a shallow copy of this object because value types are passed by value.

def end(n = 0) : Int32 #

Returns the position of the next character after the match.

When n is `0` or not given, uses the match of the entire `Regex`. Otherwise, uses the match of the nth capture group.

Raises `IndexError` if the index is out of range or the respective subpattern is unused.

    "Crystal".match(/r/).not_nil!.end(0)     # => 2
    "Crystal".match(/r(ys)/).not_nil!.end(1) # => 4
    "クリスタル".match(/リ(ス)/).not_nil!.end(0)    # => 3
    "Crystal".match(/r/).not_nil!.end(1)     # IndexError: Invalid capture group index: 1
    "Crystal".match(/r(x)?/).not_nil!.end(1) # IndexError: Capture group 1 was not matched

def group_size : Int32 #

Returns the number of capture groups, including named capture groups.

    "Crystal".match(/[p-s]/).not_nil!.group_size          # => 0
    "Crystal".match(/r(ys)/).not_nil!.group_size          # => 1
    "Crystal".match(/r(ys)(?<ok>ta)/).not_nil!.group_size # => 2

def hash(hasher) #

See `Object#hash(hasher)`

def inspect(io : IO) : Nil #
Description copied from struct Struct

Appends this struct's name and instance variables names and values to the given IO.

    struct Point
      def initialize(@x : Int32, @y : Int32)
      end
    end

    p1 = Point.new 1, 2
    p1.to_s    # "Point(@x=1, @y=2)"
    p1.inspect # "Point(@x=1, @y=2)"

def named_captures : Hash(String, String | Nil) #

Returns a hash of named capture groups.

    match = "Crystal".match(/(Cr)(?<name1>y)(st)(?<name2>al)/).not_nil!
    match.named_captures # => {"name1" => "y", "name2" => "al"}

    # When this regex has an optional group, result hash may contain
    # a `nil` if this group is not matched.
    match = "Crystal".match(/(?<name1>Cr)(?<name2>stal)?/).not_nil!
    match.named_captures # => {"name1" => "Cr", "name2" => nil}

def post_match : String #

Returns the part of the original string after the match. If the match ends at the end of the string, returns the empty string.

    "Crystal".match(/yst/).not_nil!.post_match # => "al"

def pre_match : String #

Returns the part of the original string before the match. If the match starts at the start of the string, returns the empty string.

    "Crystal".match(/yst/).not_nil!.pre_match # => "Cr"

def pretty_print(pp) : Nil #
def regex : Regex #

Returns the original regular expression.

    "Crystal".match(/[p-s]/).not_nil!.regex # => /[p-s]/

def size : Int32 #

Returns the number of elements in this match object.

    "Crystal".match(/[p-s]/).not_nil!.size          # => 1
    "Crystal".match(/r(ys)/).not_nil!.size          # => 2
    "Crystal".match(/r(ys)(?<ok>ta)/).not_nil!.size # => 3

def string : String #

Returns the original string.

    "Crystal".match(/[p-s]/).not_nil!.string # => "Crystal"

def to_a : Array(String | Nil) #

Convert this match data into an array.

    match = "Crystal".match(/(Cr)(?<name1>y)(st)(?<name2>al)/).not_nil!
    match.to_a # => ["Crystal", "Cr", "y", "st", "al"]

    # When this regex has an optional group, result array may contain
    # a `nil` if this group is not matched.
    match = "Crystal".match(/(Cr)(?<name1>stal)?/).not_nil!
    match.to_a # => ["Cr", "Cr", nil]

def to_h : Hash(Int32 | String, String | Nil) #

Convert this match data into a hash.

    match = "Crystal".match(/(Cr)(?<name1>y)(st)(?<name2>al)/).not_nil!
    match.to_h # => {0 => "Crystal", 1 => "Cr", "name1" => "y", 3 => "st", "name2" => "al"}

    # When this regex has an optional group, result array may contain
    # a `nil` if this group is not matched.
    match = "Crystal".match(/(Cr)(?<name1>stal)?/).not_nil!
    match.to_h # => {0 => "Cr", 1 => "Cr", "name1" => nil}

def to_s(io : IO) : Nil #
Description copied from struct Struct

Same as `#inspect(io)`.