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?
=~ 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.
[] 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 .
$ 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.
(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.
Use the rindex method on your string. Like this:
>> 'ssBssBss'.rindex(/B/)
=> 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With