Search code examples
ruby-on-railsrubyregexlastindexof

How do I find the index in a string of where my nth occurrence of a regex ends?


Using Rails 5.0.1 with Ruby 2.4. How do I find the index in a string of where the nth occurrence of a regex ends? If my regex were

/\-/

and my string where

str = "a -b -c"

and I were looking for the last index of the second occurrence of my regex, I would expect the answer to be 5. I tried this

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

but was greeted with the error

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

In the above, n is an integer that represents the nth occurrence of the regex I wish to scan for.


Solution

  • From my comments that grew from a link to a related question:

    The answer to that question

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

    Can easily be adapted to get the MatchData for a single item

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

    to find the nth match in a string.