Bug #17118
closedString#index and #rindex return wrong result for Regexp patterns containing /\K/
Description
When the pattern Regexp given to String#index
and String#rindex
contain a /\K/
(lookbehind) operator, these methods return the position where the beginning of the lookbehind pattern matches, while they are expected to return the position where the \K
matches.
# expected -- index of "c" is returned
"abcdbce".index(/b\Kc/) # => 2
"abcdbce".rindex(/b\Kc/) # => 5
# actual -- index of "b" is returned
"abcdbce".index(/b\Kc/) # => 1
"abcdbce".rindex(/b\Kc/) # => 4
Updated by hanazuki (Kasumi Hanazuki) about 4 years ago
Updated by hanazuki (Kasumi Hanazuki) about 4 years ago
- Status changed from Open to Closed
Applied in changeset git|014a4fda54cb6897ed54ea9c44376db3459fc46e.
rb_str_{index,rindex}_m: Handle /\K/ in pattern
When the pattern Regexp given to String#index and String#rindex
contain a /\K/ (lookbehind) operator, these methods return the
position where the beginning of the lookbehind pattern matches, while
they are expected to return the position where the \K matches.
# without patch
"abcdbce".index(/b\Kc/) # => 1
"abcdbce".rindex(/b\Kc/) # => 4
This patch fixes this problem by using BEG(0) instead of the return
value of rb_reg_search.
# with patch
"abcdbce".index(/b\Kc/) # => 2
"abcdbce".rindex(/b\Kc/) # => 5
Fixes [Bug #17118]