title: Finding the last (rightmost) match for an arbitrary regular expression in ruby
body: <p>I'm working on a text editor in ruby, and I need to support a "Find" feature with user-provided regular expression patterns.  Here's a simple (familiar) use-case:</p>
  
  <blockquote>
    <p>Joe User is editing a text file, and has positioned the cursor somewhere in the middle of the file.  He wants to search <em>backwards</em> from the current cursor location for the nearest substring matching an arbitrary regular expression.</p>
  </blockquote>
  
  <p>I'm thinking that this problem amounts to applying the user's pattern to the entire string preceding the cursor-location in the file.  Sure, I could loop through all matches from the beginning of the file and use the last match, but this seems painfully inefficient...  It would be better to search "right to left," but I haven't found a way to do this with ruby Regexp.  Can you help?</p>