我希望能够使用 Ruby 找到较大字符串中所有出现的子字符串的索引。例如:“爱因斯坦”中的所有“in”
str = "Einstein"
str.index("in") #returns only 1
str.scan("in") #returns ["in","in"]
#desired output would be [1, 6]
最佳答案
标准黑客是:
indices = "Einstein".enum_for(:scan, /(?=in)/).map do
Regexp.last_match.offset(0).first
end
#=> [1, 6]
关于ruby - 查找字符串中子字符串的所有索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43329481/