LoginSignup
2
2

More than 5 years have passed since last update.

Rubyの文字列を正規表現化する際の罠

Last updated at Posted at 2015-02-25

みなさんはRubyで正規表現を生成するときに、どうやりますか?

hoge.rb
if /hoge/ =~ "hoge"

これを、複数個やりたい場合、

hoge.rb
["hoge", "huga"].select{|i| /#{i}/ =~ "hoge" }

とかやりますよね?
ここでの i をそのまま使うと、罠を踏みます。

[1] pry(main)> hoge = "http://google.com"; /#{hoge}/
=> /http:\/\/google.com/
[2] pry(main)> /#{hoge}/ =~ "http://google.com"
=> 0

そう、 . がエスケープされないのです。
URLを簡易的にパースしようとすると、 http://google1com などがマッチしてしまって、意図しない動作になることがあります。

解決策としては
http://docs.ruby-lang.org/ja/2.2.0/method/Regexp/s/escape.html を使うことです

[2] pry(main)> /#{Regexp.escape hoge}/ =~ "http://google1com"
=> nil

これで正しく弾くことが出来ます。

2
2
1

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
2
2