LoginSignup
1
2

More than 3 years have passed since last update.

複数の正規表現にmatchするかの判定

Posted at

こんな正規表現のバリデーションメソッドがあった時、

  def customer_number_valid_format?
    return true if a.blank?
    return true if b.blank?
    binding.pry
   regex = /\A(\d{5})-?(\d{5})-?(\d{1})-?(\d{2})\z/, /\A(\d{4})-?(\d{3})-?(\d{3})\z/
  # p regex => [/\A(\d{5})-?(\d{5})-?(\d{1})-?(\d{2})\z/, /\A(\d{4})-?(\d{3})-?(\d{3})\z/]
    return true if regex.blank?
    unless customer_number.match?(regex)  🌠
      self.errors.add(:customer_number, :invalid_and_confirm, target: 'お客様番号')
    end
  end
unless customer_number.match?(regex)

ここでcustomer_number12345-12345-1-121234-123-123の時にtrueを返して欲しいが上記コードだと

[27] pry(#<Order>)> customer_number.match?(regex)
TypeError: wrong argument type Array (expected Regexp)

となる。
match?はStringクラスのメソッドだからだね。
https://docs.ruby-lang.org/ja/latest/method/String/i/match=3f.html

解決

配列に入ってるどっちかの正規表現にあってるか判定するにはRegexp.unionというものを使うらしい。

customer_number.match?(Regexp.union(regex))
[25] pry(#<Order>)> Regexp.union(regex)
=> /(?-mix:\A(\d{5})-?(\d{5})-?(\d{1})-?(\d{2})\z)|(?-mix:\A(\d{4})-?(\d{3})-?(\d{3})\z)/
# 配列ではなくパイプで繋がれ他文字列になる

[26] pry(#<Order>)> low_voltage_customer_number.match?(Regexp.union(regex))
=> true

参考: 配列を渡して正規表現オブジェクトをつくる

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