Index and last index a pattern : index « String « Ruby






Index and last index a pattern


text = "hello world"
pattern = /l/
first = text.index(pattern)       # 2: first match starts at char 2
n = Regexp.last_match.end(0)      # 3: end position of first match
second = text.index(pattern, n)   # 3: search again from there
last = text.rindex(pattern)       # 9: rindex searches backward from end

 








Related examples in the same category

1.The index method returns the index location of a matching substring.
2.line[line.index("k")]
3.Replace first vowel with an asterisk