ruby - 在 ruby​​ 中查找任意正则表达式的最后(最右边)匹配

标签 ruby regex reverse

我正在用 ruby​​ 开发一个文本编辑器,我需要使用用户提供的正则表达式模式来支持“查找”功能。这是一个简单(熟悉的)用例:

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.

我认为这个问题相当于将用户的模式应用于文件中光标位置之前的整个字符串。当然,我可以从文件开头循环遍历所有匹配项并使用最后一个匹配项,但这似乎效率很低......最好搜索“从右到左”,但我还没有找到办法这与 ruby 正则表达式。你能帮忙吗?

最佳答案

在您的字符串上使用 rindex 方法。像这样:

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

关于ruby - 在 ruby​​ 中查找任意正则表达式的最后(最右边)匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/814213/

相关文章:

Python 3 正则表达式问题

java - 为什么我的代码不起作用?

mysql - mysql中数字的反转

java - 使用基于 LinkedList 的堆栈反转字符串

list - 无法推断 (an ~ [a])

ruby-on-rails - 如何返回数组中的最新记录

ruby - 如何在 Ruby 中混合 Paperclip has_attached_file 方法?

php - preg_replace 来自文本的 src img

ruby - 如何检查 ruby​​ 代码中的 ruby​​ 语法错误

ruby-on-rails - Rails 5 - 使用 Pundit Scopes 和 Statesman 状态机 : structurally incompatible?