Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 679
joshng Avatar asked May 02 '09 05:05

joshng


People also ask

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.


1 Answers

Use the rindex method on your string. Like this:

>> 'ssBssBss'.rindex(/B/)
=> 5
like image 147
ibz Avatar answered Nov 10 '22 01:11

ibz