i要么需要找到MatchData
对象的长度,要么需要找到所找到的字符串中的最后一个元素的索引。这样我就可以插入另一个字符串。
发现的字符串的长度未知,因为此代码将在许多不同的网站上运行。
我拉下了一个字符串(它是液体模板,需要保持液体,不能转换为HTML,因此Nokogiri不是一个选择)
我要搜索的字符串是一个可能是任何长度的表单标签,在此示例中,它看起来像:
<form action="/cart" method="post" novalidate class="cart-wrapper">
我也可以找到这样的第一个元素的索引:
string.index(/<form.*>/)
我尝试使用rindex
,但它返回了与index
我可以像这样返回表单标签:
found = string.match(/<form.*>/)
以上返回MatchData
对象,但是如果我这样做:
found.size
found.length
它返回的只是 1
我的想法是获取form
标签的索引,然后添加表单标签本身中的字符数,然后在此之后插入我的字符串。但是由于某种原因,我找不到最后一个字符的索引或MatchData
的长度。
我在哪里误入歧途?
尝试这个,
last_index = str.index(/<form.*>/) + str[/<form.*>/].size
这是如何工作的?
-
str.index
返回正则索引 -
str.[...]
返回比赛本身 -
size
获得匹配的长度
但是,
看起来您正在操纵HTML字符串。最好使用nokogiri
宝石
require 'nokogiri'
doc = Nokogiri::HTML(str)
form = doc.at('form')
form.inner_html = '<div>new content</div>' + form.inner_html
puts doc
此附加form
标签中的新内容。
您可以按如下插入字符串。
def insert_str(str, regex, insert_str)
idx = str.match(regex).end(0)
return nil if idx.nil?
str[0,idx]+insert_str+str[idx..-1]
end
str = '<form action="/cart" method="post" novalidate class="cart-wrapper">'
#=> "<form action="/cart" method="post" novalidate class="cart-wrapper">"
insert_str(str, /<form.*>/, "cat")
#=> "<form action="/cart" method="post" novalidate class="cart-wrapper">cat"
str
#=> "<form action="/cart" method="post" novalidate class="cart-wrapper">"
insert_str("How now, brown cow?", /bbrownb/, " or blue")
#=> "How now, brown or blue cow?"
请参阅MatchData#结束。如果您想突变str
,请按以下方式修改该方法。
def insert_str(str, regex, insert_str)
idx = str.match(regex).end(0)
return nil if idx.nil?
str.insert(idx, insert_str)
end
str = '<form action="/cart" method="post" novalidate class="cart-wrapper">'
insert_str(str, /<form.*>/, "cat")
#=> "<form action="/cart" method="post" novalidate class="cart-wrapper">cat"
str
#=> "<form action="/cart" method="post" novalidate class="cart-wrapper">cat"