Project

General

Profile

Actions

Bug #17118

closed

String#index and #rindex return wrong result for Regexp patterns containing /\K/

Added by hanazuki (Kasumi Hanazuki) over 3 years ago. Updated over 3 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.8.0dev (2020-08-13T01:14:20Z master 69b5241c36) [x86_64-linux]
[ruby-core:99576]

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
Actions #2

Updated by hanazuki (Kasumi Hanazuki) over 3 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]

Actions

Also available in: Atom PDF

Like0
Like0Like0