Project

General

Profile

Actions

Feature #15496

open

Extract between string as standard String api

Added by macdevign (Macdevign mac) over 2 years ago. Updated over 2 years ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:90851]

Description

I could not find the a simple String api to extract the string between two string, and I notice that many face the same issue and endup rolling their own solutions (eg https://stackoverflow.com/questions/9661478/how-to-return-the-substring-of-a-string-between-two-strings-in-ruby).

Given that string "between" extraction is such a common operation, will adding a focused and simplified String method make coding pleasant ?

This is my solution but probably someone can provide better and efficient implementation.

  # self: String instance, 
  # from: String -> first 'from' String  
  # to: String -> first 'to' String found after 'from'
  # ignore_case: Boolean -> to indicate case-sensitive search
  # from_index: Integer -> Position of 'From' string to start search from
  # return string between from and to, which exclude the argument, nil otherwise.

    def between(from, to, ignore_case: false, from_index: 0)
      str = self
      str, from, to = str.downcase, from.downcase, to.downcase if ignore_case

      from_idx = str.index(from, from_index)&.+(from.length)
      if from_idx
        to_idx = str.index(to, from_idx)
        return str[from_idx...to_idx] if to_idx
      end
      nil
    end

Test case

"Hello world".between("ell", "ld") => "o wor"
"Testing 123".between("Te", "123") => "sting "
"Testing 123".between("te", "123") => nil
"Testing 123".between("te", "123", ignore_case: true) => "sting "
"Testing 123".between("te", "123", from_index: 3) => nil

Actions

Also available in: Atom PDF