singleton method Regexp.compile

compile(string, option = nil, code = nil) -> Regexp[permalink][rdoc][edit]
new(string, option = nil, code = nil) -> Regexp

文字列 string をコンパイルして正規表現オブジェクトを生成して返します。

第一引数が正規表現であれば第一引数を複製して返します。第二、第三引数は警告の上無視されます。

[PARAM] string:
正規表現を文字列として与えます。
[PARAM] option:
Regexp::IGNORECASE, Regexp::MULTILINE, Regexp::EXTENDED の論理和を指定します。 Integer 以外であれば真偽値の指定として見なされ、真(nil, false 以外)であれば Regexp::IGNORECASE の指定と同じになります。
[PARAM] code:
"n", "N" が与えられた時には、生成された正規表現のエンコーディングは ASCII-8BIT になります。それ以外の指定は警告を出力します。
[EXCEPTION] RegexpError:
正規表現のコンパイルに失敗した場合発生します。


str = "This is Regexp"
t1 = Regexp.compile("this is regexp", Regexp::IGNORECASE)
t1.match(str)
p $~ # => "This is Regexp"

t2 = Regexp.compile('
this         # ここは使用されない
\ is
\ regexp     # ここも使用されない
', Regexp::EXTENDED | Regexp::IGNORECASE)
t2.match(str)
p Regexp.last_match # => "This is Regexp"

str = "ふるいけや\nかわずとびこむ\nみずのおと"
t2 = Regexp.compile("ふる.*?と", Regexp::MULTILINE)
p t2.match(str)[0]  # => "ふるいけや\nかわずと"