From 4f19666e8b144600e959e4673f79d63f98bd637d Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Thu, 16 Jan 2020 11:25:43 +0900 Subject: [PATCH] `Regexp` in `MatchData` can be `nil` `String#sub` with a string pattern defers creating a `Regexp` until `MatchData#regexp` creates a `Regexp` from the matched string. `Regexp#last_match(group_name)` accessed its content without creating the `Regexp` though. [Bug #16508] --- re.c | 1 + test/ruby/test_regexp.rb | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/re.c b/re.c index 3efd540359..44418ec064 100644 --- a/re.c +++ b/re.c @@ -1912,6 +1912,7 @@ match_captures(VALUE match) static int name_to_backref_number(struct re_registers *regs, VALUE regexp, const char* name, const char* name_end) { + if (NIL_P(regexp)) return -1; return onig_name_to_backref_number(RREGEXP_PTR(regexp), (const unsigned char *)name, (const unsigned char *)name_end, regs); } diff --git a/test/ruby/test_regexp.rb b/test/ruby/test_regexp.rb index 39577bd75d..231fd392d1 100644 --- a/test/ruby/test_regexp.rb +++ b/test/ruby/test_regexp.rb @@ -161,6 +161,10 @@ class TestRegexp < Test::Unit::TestCase s = "foo" s[/(?o)/, "bar"] = "baz" assert_equal("fbazo", s) + + /.*/ =~ "abc" + "a".sub("a", "") + assert_raise(IndexError) {Regexp.last_match(:_id)} end def test_named_capture_with_nul