0

将 Rails 5.0.1 与 Ruby 2.4 一起使用。如何在第 n 次出现正则表达式的字符串中找到索引?如果我的正则表达式是

/\-/

我的字符串在哪里

str = "a -b -c"

我正在寻找我的正则表达式第二次出现的最后一个索引,我希望答案是 5。我试过这个

str.scan(StringHelper::MULTI_WHITE_SPACE_REGEX)[n].offset(1)

但遇到了错误

NoMethodError: undefined method `offset' for "             ":String

在上面,n 是一个整数,表示我希望扫描的正则表达式的第 n 次出现。

4

3 回答 3

0

这样做的一种方法:

def index_of_char str, char, n
  res = str.chars.zip(0..str.size).select { |a,b| a == char }
  res[n]&.last
end

index_of_char "a -b -c", '-', 0
#=> 2

index_of_char "a -b -c", '-', 1
#=> 5

index_of_char "a -b -c", '-', 2
#=> nil

index_of_char "abc", '-', 1
#=> nil

可以进行进一步优化。

于 2017-07-10T21:57:54.853 回答
0

很抱歉之前的快速阅读。也许这种方法可以帮助您定位元素的第 n 个出现的索引。虽然我找不到在 ruby​​ 中使用严格的正则表达式来做到这一点的方法。希望这可以帮助。

def index_of_nth_occorunce(string, element, nth_occurunce)
  count = 0
  string.split("").each_with_index do |elm, index| 
    count += 1 if elm == element
    return index if count == nth_occurunce
  end
end

index_of_nth_occorunce("a -b -c", "-", 2) #5

在做了一些进一步的挖掘之后,我可能已经在这个堆栈帖子中找到了你正在寻找的答案(ruby​​ regex: match and get position(s) of)。希望这也有帮助。

nth_occurence = 2 
s = "a -b -c"
positions = s.enum_for(:scan, /-/).map { Regexp.last_match.begin(0) }
p positions[nth_occurence - 1] # 5
于 2017-07-10T22:25:26.020 回答
0

从我从链接到相关问题的评论中:

这个问题的答案

"abc12def34ghijklmno567pqrs".to_enum(:scan, /\d+/).map { Regexp.last_match }

可以很容易地适应获取单个项目的 MatchData

string.to_enum(:scan, regex).map { Regexp.last_match }[n - 1].offset(0)

在字符串中查找n匹配项。

于 2017-07-10T22:59:25.110 回答