Tbpgr Blog

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

Ruby | Regexp | compile

概要

Regexp#compile(string, option = nil, code = nil) -> Regexp
Regexp#new(string, option = nil, code = nil) -> Regexp

詳細

文字列 string をコンパイルして正規表現オブジェクトを生成して返却。
第一引数が正規表現であれば第一引数を複製して返します。第二、第三引数は警告の上無視されます。

サンプルコード
require 'tbpgr_utils'

r = Regexp.compile("hoge")
ri = Regexp.compile("hoge", Regexp::IGNORECASE)
rr = Regexp.compile(/H.Ge/i, Regexp::IGNORECASE)
bulk_puts_eval binding, <<-EOS
Regexp.compile("hoge")
Regexp.compile("hoge") == /hoge/
Regexp.new("hoge") == /hoge/
r.match("hoge")
r.match("HoGe")
Regexp.compile("HoGe", Regexp::IGNORECASE)
Regexp.compile("HoGe", Regexp::IGNORECASE) == /HoGe/i
Regexp.new("HoGe", Regexp::IGNORECASE) == /HoGe/i
ri.match("HoGe")
Regexp.compile(/H.Ge/i, Regexp::IGNORECASE)
Regexp.compile(/H.Ge/i, Regexp::IGNORECASE) == /H.Ge/i
Regexp.new(/H.Ge/i, Regexp::IGNORECASE) == /H.Ge/i
rr.match("HoGe")
rr.match("HiGe")
rr.match("HaGe")
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

/path/to/code/regexp_compile.rb:5: warning: flags ignored
/path/to/code/regexp_compile.rb:6: warning: flags ignored
/path/to/code/regexp_compile.rb:6: warning: flags ignored
/path/to/code/regexp_compile.rb:6: warning: flags ignored
Regexp.compile("hoge")                                 # => /hoge/
Regexp.compile("hoge") == /hoge/                       # => true
Regexp.new("hoge") == /hoge/                           # => true
r.match("hoge")                                        # => #<MatchData "hoge">
r.match("HoGe")                                        # => nil
Regexp.compile("HoGe", Regexp::IGNORECASE)             # => /HoGe/i
Regexp.compile("HoGe", Regexp::IGNORECASE) == /HoGe/i  # => true
Regexp.new("HoGe", Regexp::IGNORECASE) == /HoGe/i      # => true
ri.match("HoGe")                                       # => #<MatchData "HoGe">
Regexp.compile(/H.Ge/i, Regexp::IGNORECASE)            # => /H.Ge/i
Regexp.compile(/H.Ge/i, Regexp::IGNORECASE) == /H.Ge/i # => true
Regexp.new(/H.Ge/i, Regexp::IGNORECASE) == /H.Ge/i     # => true
rr.match("HoGe")                                       # => #<MatchData "HoGe">
rr.match("HiGe")                                       # => #<MatchData "HiGe">
rr.match("HaGe")                                       # => #<MatchData "HaGe">