LoginSignup
1
1

More than 5 years have passed since last update.

Regexp#+を定義して「または」を簡単に作る

Posted at

「AまたはB」のような正規表現を簡単に作ろうと思って以下のようにしてみたら、うまくいかなかった。

001 > /qiita/ + /kobito/
NoMethodError: undefined method `+' for /qiita/:Regexp

意外にもRegexp#+が定義されてなかったので、以下のようにクラスを拡張してみた。

class Regexp
  def +(other)
    Regexp.new(self.source + '|' + other.source)
  end
end

Regexp#sourceはその正規表現の文字列を返すメソッド。で、期待通りにうまくいった。

002 > /qiita/ + /kobito/
=> /qiita|kobito/
1
1
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
1
1