gpt4 book ai didi

ruby - 如何使用预先清理过的索引对字符串进行索引?

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

我有一个字符串 definition ,其中可以出现 HTML,以及一个单词数组。我正在尝试在 definition 中搜索这些词并返回开始和结束位置。例如,我可能想查找 "Hello"在:

definition = "<strong>Hel</strong>lo World!"

可以使用 ActionView 中的 sanitize 来删除 HTML和 HTMLEntities , 但这改变了 "Hello" 的索引在字符串中,所以:

sanitized_definition.index("Hello")

将返回 0 .我需要起点是 8 , 和终点 21 .我考虑过将整个字符串映射到我自己的索引,例如

{"1" => '<', "2" => 's', "3" => 't', .. , "9" => 'H' ...}

因此 1 映射到第一个字符,2 映射到第二个字符,依此类推,但我不确定它完成了什么,而且它看起来过于复杂。有没有人知道如何实现这一目标?

编辑:

评论中的要点是我想包含 </strong> 没有意义, 但不是 <strong>一开始,部分原因是我还没有弄清楚如何处理这种边缘情况。出于这个问题的目的,一个更好的例子可能是这样的

definition = "Probati<strong>onary Peri</strong>od."
search_text = 'Probationary Period'

此外,在仔细考虑之后,我认为在我的特殊情况下,我唯一需要担心的 html 实体是 &nbsp; .

最佳答案

我承认我不太了解 HTML。我假设目标词(此处为“Hello”)的每个相邻字母对由零个或多个由 < 括起来的字符串分隔和 >没有别的(但不知道这是否正确)。

def doit(str, word)
r = Regexp.new(word.chars.join('(?:<.*?>)*'))
ndx = str.index(r)
ndx ? [ndx, ndx+str[r].size-1] : nil
end

doit "<strong>Hel</strong>lo World!", "Hello"
#=> [8,21]

这是发生了什么:

str  = "<strong>Hel</strong>lo World!"
word = "Hello"

a = word.chars
#=> ["H", "e", "l", "l", "o"]
s = a.join('(?:<.*?>)*')
#=> "H(?:<.*?>)*e(?:<.*?>)*l(?:<.*?>)*l(?:<.*?>)*o"
r = Regexp.new(s)
#=> /H(?:<.*?>)*e(?:<.*?>)*l(?:<.*?>)*l(?:<.*?>)*o/
ndx = str.index(r)
#=> 8
t = str[r]
#=> "Hel</strong>lo"
o = t.size-1
#=> 13
ndx ? [ndx, ndx+str[r].size-1] : nil
#=> 8 ? [8, 8 + t.size-1] : nil
#=> [8, 8 + 14 -1]
#=> [8, 21]

关于ruby - 如何使用预先清理过的索引对字符串进行索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31795941/

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