Project

General

Profile

Actions

Bug #18415

closed

String#rpartition is not sufficiently greedy compared to String#partition

Added by jdashton (J Daniel Ashton) almost 3 years ago. Updated over 2 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.1.0preview1 (2021-11-09 master 5a3b2e6141) [x86_64-darwin21]
[ruby-core:106728]

Description

3.1.0-preview1 :043 > "...999...".partition /\d+/
 => ["...", "999", "..."] 
3.1.0-preview1 :044 > "...999...".rpartition /\d+/
 => ["...99", "9", "..."] 

Using the regex /\d+/, partition gives you all consecutive digits. However, rpartition gives only the last digit.

Updated by sawa (Tsuyoshi Sawada) almost 3 years ago

I think the actual result is expected. It is partition's responsibility to match the left-most position possible, and it is +'s responsibility to match as long as possible from that position. Likewise, it is rpartition's responsibility to match the right-most position possible, and it is +'s responsibility to match as long as possible from that position. ["...99", "9", "..."] matches at index 5, which is more right than the index given by partitioning into ["...", "999", "..."], which is 3. And since matching starts at index 5, there is no extending of the match to index 6, which is ..

If you want to match 999 with rpartition, you need to do something like:

"...999...".rpartition(/(?<!\d)\d+/)
# => ["...", "999", "..."]

Updated by nobu (Nobuyoshi Nakada) almost 3 years ago

  • Backport changed from 2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN to 2.6: UNKNOWN, 2.7: REQUIRED, 3.0: REQUIRED

I agree that this is intentional and a documentation matter.

Actions #3

Updated by nobu (Nobuyoshi Nakada) almost 3 years ago

  • Status changed from Open to Closed

Applied in changeset git|e2ec97c4b823a0b2e0c31e7a6d77b1dcdc0dfada.


[DOC] How to get the longest last match [Bug #18415]

Updated by nagachika (Tomoyuki Chikanaga) over 2 years ago

  • Backport changed from 2.6: UNKNOWN, 2.7: REQUIRED, 3.0: REQUIRED to 2.6: UNKNOWN, 2.7: REQUIRED, 3.0: DONE

ruby_3_0 4b1cee1431b44e923611c65a8ec5cc61d4025641 merged revision(s) e2ec97c4b823a0b2e0c31e7a6d77b1dcdc0dfada.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0