Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Regexp | union

概要

Regexp.union(*pattern) -> Regexp

詳細

引数として与えた pattern を選択 | で連結し、Regexp として返却。
結果の Regexp は与えた pattern のどれかにマッチする場合にマッチするものになります。

サンプルコード
require 'tbpgr_utils'


bulk_puts_eval binding, <<-EOS
Regexp.union(/h.ge/, /b.r/, /h.o/)
Regexp.union([/h.ge/, /b.r/, /h.o/])
Regexp.union("h.ge", "b.r", "h.o") # String を指定されるとエスケープして正規表現に変換される
Regexp.union
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

Regexp.union(/h.ge/, /b.r/, /h.o/)   # => /(?-mix:h.ge)|(?-mix:b.r)|(?-mix:h.o)/
Regexp.union([/h.ge/, /b.r/, /h.o/]) # => /(?-mix:h.ge)|(?-mix:b.r)|(?-mix:h.o)/
Regexp.union("h.ge", "b.r", "h.o")   # String を指定されるとエスケープして正規表現に変換される # => /h\.ge|b\.r|h\.o/
Regexp.union                         # => /(?!)/