End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
class method
Regexp.new
Regexp.new(string, [options]) → regexp
Regexp.new(regexp) → regexp
Regexp.compile(string, [options]) → regexp
Regexp.compile(regexp) → regexp
re.c
View on GitHub ↗
static VALUE
rb_reg_initialize_m(int argc, VALUE *argv, VALUE self)
{
int flags = 0;
VALUE str;
rb_encoding *enc = 0;
rb_check_arity(argc, 1, 3);
if (RB_TYPE_P(argv[0], T_REGEXP)) {
VALUE re = argv[0];
if (argc > 1) {
rb_warn("flags ignored");
}
rb_reg_check(re);
flags = rb_reg_options(re);
str = RREGEXP_SRC(re);
}
else {
if (argc >= 2) {
if (FIXNUM_P(argv[1])) flags = FIX2INT(argv[1]);
else if (RTEST(argv[1])) flags = ONIG_OPTION_IGNORECASE;
}
if (argc == 3 && !NIL_P(argv[2])) {
char *kcode = StringValuePtr(argv[2]);
if (kcode[0] == 'n' || kcode[0] == 'N') {
enc = rb_ascii8bit_encoding();
flags |= ARG_ENCODING_NONE;
}
else {
rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "encoding option is ignored - %s", kcode);
}
}
str = StringValue(argv[0]);
}
if (enc && rb_enc_get(str) != enc)
rb_reg_init_str_enc(self, str, enc, flags);
else
rb_reg_init_str(self, str, flags);
return self;
}
Constructs a new regular expression from pattern, which can be either a String or a Regexp (in which case that regexp’s options are propagated), and new options may not be specified (a change as of Ruby 1.8).
If options is an Integer, it should be one or more of the constants Regexp::EXTENDED, Regexp::IGNORECASE, and Regexp::MULTILINE, or-ed together. Otherwise, if options is not nil or false, the regexp will be case insensitive.
Example
r1 = Regexp.new('^a-z+:\\s+\w+') #=> /^a-z+:\s+\w+/ r2 = Regexp.new('cat', true) #=> /cat/i r3 = Regexp.new(r2) #=> /cat/i r4 = Regexp.new('dog', Regexp::EXTENDED | Regexp::IGNORECASE) #=> /dog/ix