Tbpgr Blog

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

Ruby | Regexp | =~

概要

Regexp#=~ string -> Fixnum | nil

詳細

文字列 string との正規表現マッチを行います。

マッチした場合 |> マッチした位置のインデックスを返却
マッチしなかった場合 |> nil を返却。
String が nil の場合 |> nil を返却。

サンプルコード
require 'tbpgr_utils'


bulk_puts_eval binding, <<-EOS
/h.ge/=~"hoge"
/h.ge/=~"hige"
/h.ge/=~"testhage"
/h.ge/=~"hoo"
/h.ge/=~nil
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

/h.ge/=~"hoge"     # => 0
/h.ge/=~"hige"     # => 0
/h.ge/=~"testhage" # => 4
/h.ge/=~"hoo"      # => nil
/h.ge/=~nil        # => nil