2012-09-26 58 views
1

以下用途gsub,我預計"No, but I heard it's short and soft."被放置在塊引號之間。第一次,它是空的。當我立即再次運行它時,它是正確的。Gsub第一次失敗,下一步工作?

clean_content = "[quote="PDrizzle":1g581fap]No, but I heard it's short and soft.[/quote:1g581fap]\r\n\r\nwith very few ascents\r\n\r\nheh" 
clean_content.gsub(
    /\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/, 
    "<blockquote>#{$1}</blockquote>" 
) 
# => "<blockquote></blockquote>\r\n\r\nwith very few ascents\r\n\r\nheh" 
clean_content.gsub(
    /\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/, 
    "<blockquote>#{$1}</blockquote>" 
) 
# => "<blockquote>No, but I heard it's short and soft.</blockquote>\r\n\r\nwith very few ascents\r\n\r\nheh" 

任何想法是怎麼回事?

回答

4

gsub期望替換字符串中的反向引用被格式化爲\\1而不是$1。在你的例子中,第一次發生的字符串替換是指一個變量是空字符串,而第二次是通過執行第一次模式匹配來設置的。

所以,你想:

clean_content.gsub(/\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/, "<blockquote>\\1</blockquote>") 
0

記住的論點,即評價先於把他們的方法進行評估。首先,你必須$1 = "",所以你的gsub一審相當於

gsub(
    /\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/, 
    "<blockquote></blockquote>" 
) 

這使得$1 = "No, but I heard it's short and soft.",所以當你做你的gsub秒實例相當於

gsub(
    /\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/, 
    "<blockquote>No, but I heard it's short and soft.</blockquote>" 
) 

第三次,您將再次擁有

gsub(
    /\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/, 
    "<blockquote></blockquote>" 
)