/ Published in: Ruby
Public domain. Returns n from the nth occurrence (occurrence_index) of substring in var, or -1 if var does not contain substring or occurrence_index exceeds the length of var. Does not account for overlapping substrings (one solution is to delimit substrings, such as with a space, so you can pass " or " as substring to find occurrences of "or" as a word).
See also Find the nth occurrence of a substring.
Expand |
Embed | Plain Text
def find_n_from_occurrence_index(var, substring, occurrence_index) var = var[0..occurrence_index+substring.length] return var.include?(substring) && (occurrence_index+substring.length) <= var.length ? var.scan(substring).length : -1 end
You need to login to post a comment.
