Search for the last (rightmost) match for an arbitrary regular expression in ruby

I am working on a text editor in ruby, and I need to support the Find feature using user-supplied regular expression patterns. Here is a simple (familiar) use case:

Joe A user edits a text file and positions the cursor somewhere in the middle of the file. He wants to search back from the current cursor location for the nearest substring matching an arbitrary regular expression.

I think this problem is applying the user pattern to the entire line preceding the cursor location in the file. Of course, I could iterate over all matches from the beginning of the file and use the last match, but it seems painfully inefficient ... It would be better to look from right to left, but I did not find a way to do this with the Regexp ruby. You can help?

+6
ruby regex reverse
source share
3 answers

Use the rindex method on your string. Like this:

>> 'ssBssBss'.rindex(/B/) => 5 
+11
source share

The search .*(foo) should also find the rightmost foo, thanks to its greedy nature. * (but rindex can be faster - a microobject is required to check!).

+4
source share

I think rindex is the way to go. It seems that rindex is actually looping back the line. Check line 957 string.c

It seems like someone figured out the way to reverse regular expressions in PERL back in 2001. That way you can change the line and undo regex ... then use the method from left to right.

I'm sure it is crowded now and you can go with rindex

+1
source share

All Articles