Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all indices of a substring within a string

Tags:

ruby

I want to be able to find the index of all occurrences of a substring in a larger string using Ruby. E.g.: all "in" in "Einstein"

str = "Einstein"
str.index("in") #returns only 1
str.scan("in")  #returns ["in","in"]
#desired output would be [1, 6]
like image 836
Mokhtar Avatar asked Apr 10 '17 17:04

Mokhtar


People also ask

How do you find the index of a specific string?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the index of a substring in a string C++?

string::find() function returns the index of first occurrence of given substring in this string, if there is an occurrence of substring in this string. If the given substring is not present in this string, find() returns -1.


1 Answers

The standard hack is:

indices = "Einstein".enum_for(:scan, /(?=in)/).map do
  Regexp.last_match.offset(0).first
end
#=> [1, 6]
like image 54
tokland Avatar answered Oct 19 '22 14:10

tokland