gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:02:33 27 4
gpt4 key购买 nike

我正在用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com