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.
One way of doing this:
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
Further optimisations can be made.
Sorry about the speedy read earlier. Maybe this method can help you locate the index of the nth occorunce of an element. Although I could not find a way to do this with strictly regex in ruby. Hope this helps.
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
After doing some further digging I may have found the answer you are looking for in this stack post ( ruby regex: match and get position(s) of ). Hope this also helps.
nth_occurence = 2
s = "a -b -c"
positions = s.enum_for(:scan, /-/).map { Regexp.last_match.begin(0) }
p positions[nth_occurence - 1] # 5
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 n
th match in a string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.