Question

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:

Joe User is editing a text file, and has positioned the cursor somewhere in the middle of the file. He wants to search backwards from the current cursor location for the nearest substring matching an arbitrary regular expression.

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?

Was it helpful?

Solution

Use the rindex method on your string. Like this:

>> 'ssBssBss'.rindex(/B/)
=> 5

OTHER TIPS

looking for .*(foo) should also locate the rightmost foo, thanks to the greedy nature of .* (but rindex may be faster -- needs a microbenchmark to check!).

I think rindex is the way to go. It seems like rindex will actually iterate through the string backwards. Check out line 957 of string.c

It looks like someone figured out a way to reverse regular expressions in PERL back in 2001. So you would reverse a string and reverse a regex...then use the left to right method.

I am sure that is overkill now and you can go with rindex

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top