Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Regexp | match

概要

Regexp#match(str, pos = 0) -> MatchData | nil
Regexp#match(str, pos = 0) {|m| ... } -> object | nil

詳細

指定された文字列 str に対して 位置 pos からマッチングを行う。

マッチした場合: MatchData オブジェクトを返却
マッチしなかった場合: nil を返却

ブロックを渡すと、マッチした場合に限り MatchData オブジェクトがブロック引数に渡されて実行されます

マッチした場合: MatchData ブロックの値を返却
マッチしなかった場合: nil を返却

サンプルコード
require 'tbpgr_utils'


bulk_puts_eval binding, <<-EOS
/h.ge/.match("hoge")
/h.ge/.match("hige")
/h.ge/.match("hoge", 1)
/h.ge/.match("ahoge", 1)
/(h.ge)(h.ge)(h.ge)/.match("hogehigehage") { |e|e.to_a }
/(h.ge)(h.ge)(h.ge)/.match("hogehigehage", 12) { |e|e.to_a }
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

/h.ge/.match("hoge")                                         # => #<MatchData "hoge">
/h.ge/.match("hige")                                         # => #<MatchData "hige">
/h.ge/.match("hoge", 1)                                      # => nil
/h.ge/.match("ahoge", 1)                                     # => #<MatchData "hoge">
/(h.ge)(h.ge)(h.ge)/.match("hogehigehage") { |e|e.to_a }     # => ["hogehigehage", "hoge", "hige", "hage"]
/(h.ge)(h.ge)(h.ge)/.match("hogehigehage", 12) { |e|e.to_a } # => nil