LoginSignup
46
38

More than 5 years have passed since last update.

Rubyの正規表現マッチング

Posted at

Rubyで正規表現にマッチする文字列かどうかを判定する方法はいくつかある。

str = 'foo'

# String#=~、Regexp#=~。マッチした位置かnilを返す
str =~ /o/ #=> 1
/o/ =~ str #=> 1

# String#match、Regexp#match。MatchDataかnilを返す
str.match /o/ #=> <MatchData "o">
/o/.match str #=> <MatchData "o">

# Regexp#===。trueかfalseを返す
/o/ === str #=> true

単にマッチするかどうかを判定したいだけならRegexp#===を使いましょうってパーフェクトRubyに書いてあったので、その場合はRegexp#===を使えばいいと思うけど、=~matchと違って===は右辺と左辺が変わると結果が変わるので注意が必要。

/o/ === str #=> true
str === /o/ #=> false

String#===は正規表現のマッチングじゃなくて文字列の比較になっちゃうからだね。

46
38
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
38