查找字符串中子字符串的所有索引 [英] Find all indices of a substring within a string

查看:62
本文介绍了查找字符串中子字符串的所有索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用 Ruby 在更大的字符串中找到所有出现的子字符串的索引.例如:Einstein"中的所有in"

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]

推荐答案

标准 hack 是:

indices = "Einstein".enum_for(:scan, /(?=in)/).map do
  Regexp.last_match.offset(0).first
end
#=> [1, 6]

这篇关于查找字符串中子字符串的所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆