使用Regexp获取找到的字符串的位置?

时间:2013-01-14 21:55:06

标签: ruby-on-rails ruby regex

我有一个大文字,我想在某个字符串之前删除所有内容。

问题是,文本中出现了几次该字符串,我想通过稍后分析找到的文本来决定哪一个是正确的。 由于其复杂性,我无法将该分析包含在正则表达式中:

text = <<HERE
big big text
goes here
HERE

pos = -1

a = text.scan(/some regexp/im)
a.each do |m|
  s = m[0]

  # analysis of found string
  ...


  if ( s is good ) # is the right candidate
    pos = ??? # here I'd like to have a position of the found string in the text.

  end

end

result_text = text[pos..-1]

2 个答案:

答案 0 :(得分:4)

$~.offset(n)会给出n部分匹配的位置。

答案 1 :(得分:0)

我认为您应该计算大字符串中出现的次数,然后使用index来切断与最终模式不匹配的所有事件。

相关问题