Ruby 1.8.7 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Regexpクラス > =~

instance method Regexp#=~

self =~ string -> Fixnum | nil

文字列 string との正規表現マッチを行います。マッチした場合、 マッチした位置のインデックスを返します(先頭は0)。マッチしなかった 場合、あるいは string が nil の場合には nil を返 します。

p /foo/ =~ "foo"  #=> 0
p /foo/ =~ "afoo" #=> 1
p /foo/ =~ "bar"  #=> nil

組み込み変数 $~ もしくは Regexp.last_match にマッチに関する情報 MatchData が設定されます。

[PARAM] string:
マッチ対象文字列
[EXCEPTION] TypeError:
string が nil でも String オブジェクトでもない 場合発生します。
p /foo/ =~ "foo"        #=> 0
p Regexp.last_match(0)  #=> "foo"
p /foo/ =~ "afoo"       #=> 1
p $~[0]                 #=> "foo"
p /foo/ =~ "bar"        #=> nil

unless /foo/ === "bar"
  puts "not match " #=> not match
end

str = []
begin
  /ugo/ =~ str
rescue TypeError
  printf "! %s\t%s\n", $!, $@ #=> ! can't convert Array into String       r5.rb:15
end
class Regexp