2016-12-29 34 views
0

我或者需要查找MatchData對象的長度,或者找到的字符串中最後一個元素的索引。所以我可以在它後面插入另一個字符串。查找使用REGEX找到的字符串中最後一個字符的索引

找到的字符串的長度未知,因爲此代碼將在許多不同的網站上運行。

我拉下一個字符串(它是一種液體的模板,並需要保持液態,不能轉換爲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的長度。

我在哪裏誤入歧途?

回答

2

試試這個,

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標籤內的新內容。

+0

完美..第一個工作很好..謝謝! – ToddT

0

您可以按如下方式插入字符串。

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?", /\bbrown\b/, " or blue") 
    #=> "How now, brown or blue cow?" 

參見MatchData#end。如果您想修改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" 
相關問題