From e2ec97c4b823a0b2e0c31e7a6d77b1dcdc0dfada Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 19 Dec 2021 20:12:26 +0900 Subject: [PATCH] [DOC] How to get the longest last match [Bug #18415] --- string.c | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/string.c b/string.c index 678f63781a..24acdfae0e 100644 --- a/string.c +++ b/string.c @@ -4081,7 +4081,6 @@ rb_str_rindex(VALUE str, VALUE sub, long pos) return str_rindex(str, sub, s, pos, enc); } - /* * call-seq: * rindex(substring, offset = self.length) -> integer or nil @@ -4103,6 +4102,23 @@ rb_str_rindex(VALUE str, VALUE sub, long pos) * 'foo'.rindex(/oo/) # => 1 * 'foo'.rindex(/ooo/) # => nil * + * The _last_ match means starting at the possible last position, not + * the last of longest matches. + * + * 'foo'.rindex(/o+/) # => 2 + * $~ #=> # + * + * To get the last longest match, needs to combine with negative + * lookbehind. + * + * 'foo'.rindex(/(? 1 + * $~ #=> # + * + * Or String#index with negative lookforward. + * + * 'foo'.index(/o+(?!.*o)/) # => 1 + * $~ #=> # + * * \Integer argument +offset+, if given and non-negative, specifies the maximum starting position in the * string to _end_ the search: * @@ -10395,6 +10411,20 @@ rb_str_partition(VALUE str, VALUE sep) * "hello".rpartition("l") #=> ["hel", "l", "o"] * "hello".rpartition("x") #=> ["", "", "hello"] * "hello".rpartition(/.l/) #=> ["he", "ll", "o"] + * + * The match from the end means starting at the possible last position, not + * the last of longest matches. + * + * "hello".rpartition(/l+/) #=> ["hel", "l", "o"] + * + * To partition at the last longest match, needs to combine with + * negative lookbehind. + * + * "hello".rpartition(/(? ["he", "ll", "o"] + * + * Or String#partition with negative lookforward. + * + * "hello".partition(/l+(?!.*l)/) #=> ["he", "ll", "o"] */ static VALUE